<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title></title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <link rel="stylesheet" href="../plugins/layui-v2.6.8/layui/css/layui.css?v=${.Config.basic.version}" media="all">
    <link rel="stylesheet" href="../plugins/layui/css/style.css?v=${.Config.basic.version}" media="all">
    <link rel="stylesheet" href="../layuiadmin/style/admin.css?v=${.Config.basic.version}" media="all">
    <link rel="stylesheet" href="../plugins/zTree/css/metroStyle/metroStyle.css?v=${.Config.basic.version}">
    <link rel="stylesheet" href="../plugins/zTree/css/metroStyle/ext.css?v=${.Config.basic.version}">
    <link rel="stylesheet" href="//at.alicdn.com/t/c/font_3564966_a6tt4yhnzge.css" media="all">
    <link rel="stylesheet" href="../plugins/toastr/toastr.min.css?v=${.Config.basic.version}">
    <style>
 

        .layui-form-item .layui-input-inline {
            float: left;
            width: 150px;
            margin-right: 10px;
        }
        .layui-form-item {
            margin-top: 5px;
            margin-bottom: 10px;
        }

        .layui-btn + .layui-btn {
            margin-left: 0px;
        }
        /* .layui-btn-xs {
            height: 18px;
            line-height: 18px;
            padding: 0 5px;
            font-size: 11px;
        } */


        .layui-form-label-lg {
            float: left;
            display: block;
            padding: 9px 15px;
            width: 130px;
            font-weight: 400;
            line-height: 20px;
            text-align: right;
        }

        /*.layui-form-item .layui-input[readonly] {*/
        /*    background-color: #0a1434;*/
        /*    color: #a6b8d5;*/
        /*    border: none;*/
        /*    border-top-color: currentcolor;*/
        /*    border-right-color: currentcolor;*/
        /*    border-bottom-color: currentcolor;*/
        /*    border-left-color: currentcolor;*/
        /*}*/

        /* .layui-table-view .layui-table td, .layui-table-view .layui-table th {
            padding: 5px 0;
            border-top: 1px solid #404453;
            border-left: 1px solid #404453;
            border-bottom: 1px solid #404453;
            border-right: 1px solid #404453;
        } */
        .layui-btn {
            background-color: #37384d;
        }
        

        .layui-btn-my {
            height: 25px;
            line-height: 16px;
            padding: 0 5px;
            font-size: 12px;
            border: 1px solid #ddd;
            color: #333;
            background: transparent !important;
            color: #444 !important;
        }
        .layui-btn-my:hover {
            opacity: .6;
            filter: alpha(opacity=80);
        }
        .layui-form-label-sm {
            float: left;
            display: block;
            padding: 7px 5px 7px 5px;
            width: 80px;
            font-weight: 400;
            line-height: 20px;
            text-align: center;
            font-size: 11px;
        }
        
        .layui-form-selected dl {
            max-height: 150px;
        }
        .shortGreyLine {
            /* margin: 0 2px 0 2px; */
            border-left: 1px solid #6c6c6c;
        }

        .layui-card {
            box-shadow: none;
        }

        /* .layui-table-edit{
            background-color: #ddd;
            color: #000;
            border: 1px solid #333;
        } */
    </style>

    <style>
        .layui-table-cell {
            line-height: 20px !important;
            vertical-align: middle;
            height: auto;
            overflow: visible;
            text-overflow: inherit;
            white-space: normal;
        }
        /*
        .layui-table-view .layui-table[lay-size="sm"] .layui-table-cell {
            line-height: 20px !important;
            vertical-align: middle;
            height: auto;
            overflow: visible;
            text-overflow: inherit;
            white-space: normal;
        } */

        .layui-progress {
            position: relative;
            height: 2px;
            border-radius: 20px;
            background-color: #eee;
        }
        .layui-progress-bar {
            position: absolute;
            left: 0;
            top: 0;
            width: 0;
            max-width: 100%;
            height: 2px;
            border-radius: 20px;
            text-align: right;
            background-color: #5FB878;
            transition: all .3s;
            -webkit-transition: all .3s;
        }
        /* .layui-table-grid-down {
            display: none;
        } */
        .layui-progress-big, .layui-progress-big .layui-progress-bar {
            height: 18px !important;
            line-height: 18px !important;
        }
    </style>

    <style>
        #hnum_menu{
            background-color: transparent !important;
            cursor: pointer;
            /* opacity: .5; */
        }
        #hnum_menu:hover{
            opacity: .7;
        }
        .site-dropdown-demo,
        .site-dropdown-demo .layui-menu{background-color: #666; border: none;}
        .site-dropdown-demo .layui-menu li{color: #fff;}
        .site-dropdown-demo .layui-menu li:hover{background-color: #3c7cff;}
    </style>
</head>

<body class="layui-layout-body">
<div class="layui-fluid">
    <div style="display: flex;">
        <div style="width: 250px; " >
            <div class="layui-card tree-div" >

                <div class="">
                    <div class="" >
                        <ul id="treeDemo" class="ztree"></ul>
                    </div>
                </div>
            </div>
        </div>
        <div style="width: calc(100% - 250px);float: right; " >
            <div class="layui-card">
                <div class="layui-card-body">
                    <form class="layui-form" lay-filter="form_search" id="form_search" action="">
                        <div class="layui-form-item layui-hide">

                            <div class="layui-inline" style="margin: 0;">
                                <label class="layui-form-label layui-form-label-sm" style="width: 50px;padding: 9px 2px;">模式</label>
                                <div class="layui-input-inline" style="width: 100px;">
                                    <select name="mode" lay-verify="" lay-search="">
                                        <option value=""></option>
                                        <option value="0">停用</option>
                                        <option value="1">妊娠</option>
                                        <option value="2">哺乳</option>
                                        <option value="3">保育</option>
                                        <option value="4">育肥</option>
                                        <option value="5">定时</option>
                                    </select>
                                </div>
                            </div>
                            <div class="layui-inline" style="margin: 0;">
                                <label class="layui-form-label layui-form-label-sm" style="width: 50px;padding: 9px 2px;">栏位</label>
                                <div class="layui-input-inline" style="width: 100px;">
                                    <select name="hnum" lay-verify="" lay-search="">
                                        <option value=""></option>
                                    </select>
                                </div>
                            </div>

                            <div class="layui-inline" style="margin: 0;">
                                <label class="layui-form-label layui-form-label-sm" style="width: 50px;padding: 9px 2px;">日龄</label>
                                <div class="layui-input-inline" style="width: 100px;">
                                    <input type="text" name="day" placeholder="日龄" lay-verify="" autocomplete="off" class="layui-input">
                                </div>
                            </div>

                            <div class="layui-inline" style="margin: 0;">
                                <button type="submit" class="layui-btn layui-btn-sm layui-btn-normal layui-btn-primary" id="btn_search" lay-submit="" lay-filter="btn_search"><i class="layui-icon layui-icon-search"></i>刷新</button>
                            </div>
                        </div>

                        <div class="layui-form-item">
                            <blockquote class="layui-elem-quote">
                                <span id="id-housename" style="margin-right: 10px;"></span>
                                
                                <span id="id-feedLow" style="display: none;" class="house-tip layui-badge">昨日采食低</span>
                                <span id="id-feed" style="display: none;" class="house-tip layui-badge layui-bg-green">昨日采食正常</span>
                                <span id="id-feedHigh" style="display: none;" class="house-tip layui-badge layui-bg-orange">昨日采食高</span>
                                <!-- <span id="id-calFeedErr" style="display: none;" class="house-tip layui-badge">未校准下料</span> -->
                                <!-- <span id="id-dfxwBizErr" style="display: none;" class="house-tip layui-badge ">猪群信息异常</span> -->
                                
                                <div class="layui-inline fr">
                                    <button type="submit" class="layui-btn layui-btn-my  " lay-submit="" lay-filter="btn_refresh"><i class="layui-icon layui-icon-refresh"></i> 刷新</button>
                                    <button type="submit" class="layui-btn layui-btn-my  action-edit layui-hide" lay-submit="" lay-filter="btn_apply_plan"><i class="layui-icon layui-icon-tabs-bak"></i> 应用方案</button>
                                    <button type="submit" class="layui-btn layui-btn-my  action-edit layui-hide" lay-submit="" lay-filter="btn_set_hnum"><i class="layui-icon layui-icon-slider-bak"></i> 设置栏位</button>
                                    <!-- <button type="submit" class="layui-btn layui-btn-my  action-edit layui-hide" lay-submit="" id="btn_born" lay-filter="btn_born" style="display: none;"><i class="layui-icon layui-icon-app"></i> 分娩</button> -->
                                    <button type="submit" class="layui-btn layui-btn-my  action-edit layui-hide" lay-submit="" lay-filter="btn_set_day"><i class="layui-icon layui-icon-date-bak"></i> 设置日龄</button>
                                    <button type="submit" class="layui-btn layui-btn-my  action-edit layui-hide" lay-submit="" lay-filter="btn_set_calFeed"><i class="layui-icon layui-icon-slider-bak"></i> 校准下料</button>
                                    <button type="submit" class="layui-btn layui-btn-my  action-manulfeed layui-hide" lay-submit="" lay-filter="btn_remoteFeed"><i class="layui-icon layui-icon-slider-bak"></i> 远程控制</button>
                                    <!-- <button type="submit" class="layui-btn layui-btn-my  action-edit layui-hide" lay-submit="" id="btn_set_waterPTTO" lay-filter="btn_set_waterPTTO"><i class="layui-icon layui-icon-slider"></i> 水压调整</button> -->
                                    <button type="submit" class="layui-btn layui-btn-my  action-edit layui-hide" lay-submit="" lay-filter="btn_set_stop"><i class="layui-icon layui-icon-pause"></i> 停用</button>
                                    <button type="submit" class="layui-btn layui-btn-my  action-edit layui-hide" lay-submit="" lay-filter="btn_set_enable"><i class="layui-icon layui-icon-play"></i> 启用</button>
                                    
                                </div>
                                
                            </blockquote>
                            
                            
                            
                        </div>
                    </form>



                    <table class="layui-hide" id="table" lay-filter="table"></table>
                    <script type="text/html" id="table_toolbar">
                        <div class="layui-btn-container">
                            <!-- <button class="layui-btn layui-btn-sm layui-btn-normal  action-edit layui-hide" lay-event="addDevice">增加</button> -->
                             <span class="layui-text-black layui-text-xs" id=""></span>
                                <span class="layui-badge-dot layui-bg-blue"></span> <span class="layui-text-black layui-text-xs">总计: </span> <span class="layui-text-black layui-text-xs" id="id-total">0</span><span class="shortGreyLine"></span>
                                <span class="layui-badge-dot layui-bg-black"></span> <span class="layui-text-black layui-text-xs">离线: </span> <span class="layui-text-black layui-text-xs" id="id-offline">0</span><span class="shortGreyLine"></span>
                                <span class="layui-badge-dot layui-bg-orange"></span> <span class="layui-text-black layui-text-xs">停用: </span> <span class="layui-text-black layui-text-xs" id="id-disable">0</span><span class="shortGreyLine"></span>
                                <span class="layui-badge-dot"></span> <span class="layui-text-black layui-text-xs">告警: </span> <span class="layui-text-black layui-text-xs" id="id-alarm">0</span><span class="shortGreyLine"></span>
                                <!-- <span class="layui-badge-dot layui-bg-blue"></span> <span class="layui-text-black layui-text-xs">采食合格:</span> <span class="layui-text-black layui-text-xs" id="id-disable">0</span><span class="shortGreyLine"></span> -->
                                <!-- <span class="layui-badge-dot layui-bg-orange"></span> <span class="layui-text-black layui-text-xs">采食异常:</span> <span class="layui-text-black layui-text-xs" id="id-disable">0</span> -->
                                <span class="layui-text-black layui-text-xs">日龄:</span> <span class="layui-text-black layui-text-xs" id="id-day">N/A</span><span class="shortGreyLine"></span>
                                <!-- <span class="layui-text-black layui-text-xs">MES日龄:</span> <span class="layui-text-black layui-text-xs" id="id-mesday">N/A</span><span class="shortGreyLine"></span> -->
                                <span class="layui-text-black layui-text-xs">当前存栏:</span> <span class="layui-text-black layui-text-xs" id="id-pig">N/A</span><span class="shortGreyLine"></span>
                                <!-- <span class="layui-text-black layui-text-xs">MES存栏:</span> <span class="layui-text-black layui-text-xs" id="id-mespig">N/A</span><span class="shortGreyLine"></span> -->
                                <span class="layui-text-black layui-text-xs">总采食:</span> <span class="layui-text-black layui-text-xs" id="id-sum">N/A</span><span class="shortGreyLine"></span>
                                <span class="layui-text-black layui-text-xs">头均采食:</span> <span class="layui-text-black layui-text-xs" id="id-avg">N/A</span>
                                <!-- <span class="layui-text-black layui-text-xs">温度:</span> <span class="layui-text-black layui-text-xs" id="id-temp">N/A</span> -->
                        </div>
                    </script>




                </div>
            </div>
        </div>
    </div>


</div>

<script src="../plugins/jquery/jquery-3.6.0.js?v=${.Config.basic.version}"></script>
<script src="../plugins/layui-v2.6.8/layui/layui.js"></script>
<script src="../plugins/layui/xm-select-v1.2.4.js"></script>

<!--<script src="../plugins/echart/echarts-4.8.min.js?v=${.Config.basic.version}"></script>-->
<script src="../plugins/zTree/js/jquery.ztree.core.min.js?v=${.Config.basic.version}"></script>
<script src="../plugins/zTree/js/jquery.ztree.excheck.js?v=${.Config.basic.version}"></script>
<script src="../plugins/zTree/js/jquery.ztree.exedit.js?v=${.Config.basic.version}"></script>
<!-- <script src="../plugins/echart/echarts-4.8.min.js?v=${.Config.basic.version}"></script> -->
<script src="../plugins/echart/echarts-4.8.min.js?v=${.Config.basic.version}"></script>
<script src="../plugins/jquery.slimscroll.min.js"></script>
<script src="../plugins/toastr/toastr.min.js"></script>
<script src="../plugins/moment.min.js"></script>
<script src="../js/utils.js?v=${.Config.basic.version}"></script>
<script src="../js/verify.js?v=${.Config.basic.version}"></script>
<script src="../js/func.js?v=${.Config.basic.version}"></script>
<script>
    var zTree=null;
    var table=null;
    var form=null;
    var Table=null;
    var Table1=null;
    var lay_index=null;
    var curAddr=null;
    var laydate = null;
    var element = null;
    var dropdown = null;

    var transfer=null;
    var userItems=[];
    var device_define=[];

    var czqPara=null;//终端参数
    var czqState=null;

    var fieldDictionary={
        "Gday":"日龄",
        "Mode":"模式",

        "CalFeed":"校准",
        "YlCheck":"余料检测",
        "EnWater":"水阀",

        "ManOut":"手动出料",
        "ManWaterOut":"手动出水",
        "FeedWater":"料水比",
        "AutoOut":"单次出料量",
        "Son":"带仔数",
        "Fit":"体况",
    };

    var tableOptions={};

    var nodeParaArr=[];
    var addrArr=[];
    var enableArr=[];
    var tnArr=[];
    //var feedPlanIdArr = [];
    var hnumArr=[];//下发栏位号

    var set_day=null;
    var set_pulseWater=null;
    var set_calFeed = null;
    var set_calAD = null;
    var set_calADR = null;
    var set_mode = null;
    var set_mode_arr = [];//启用模式
    var set_feed=null;
    var set_water=null;
    var feed_plan_id=null;
    var node_model = 'feed';

    var auto_hnum = false;
    var auto_hnum_prefix_idx = null;
    var auto_hnum_col = null;

    const retry_max = 3;
    var apply_run = false; //下发
    var apply_idx = 0;//下发序号
    var apply_retry = 0;
    var apply_failed_idx_arr=[];//下发失败索引数组
    var progress_index =null;//进度窗idx

    var users = [];
    var selectUser = null;
    var allData=[];//feednodes data
    var allPlanData = [];//plans data

    var token = window.localStorage.getItem("token");
    token = 'Bearer ' + token;
    var user_info=JSON.parse(window.localStorage.getItem("user_info"));
    var is_admin = user_info.is_admin;
    var group_code = user_info.group_code;
    var role_ids= user_info.role_ids;
    var func_url="${.func_url}";
    var actions=[];
    

    var SYS_PIG_TYPE=[];

    var trans_bg="10,20,52";
    var offline_color="100,100,100";
    var disable_color="0,0,0";
    var orange_color="255,222,173";
    var blue_color="0,255,255";
    var nanmu_orange_bg="242,145,20";
    var nanmu_blue_bg="0,161,186";
    var offline_bg="100,100,100";
    var white_color = "255,255,255";
    var gray_color = "200,200,200";
    var red_color = "255,0,0";
    var nanmu_orange = "#F29114";
    var nanmu_blue = "#00A1BA";
    var nanmu_green = "#33ff3d";

    const lightGreenColor = "#429c5e";
    const lightOrangeColor = "#f47011";
    const lightOrangeColor1 = "#eab839";
    const lightOrangeColor2 = "#ffee01";
    const titleColor = "#8f97b3";
    const blue="#4168ff";
    const green="#31c2b0";

    var tomorrow = moment().add(1,"days").format('YYYY-MM-DD');
    var today = moment().format('YYYY-MM-DD');
    var yestoday = moment().add(-1,"days").format('YYYY-MM-DD');
    var aweekago = moment().add(-7,"days").format('YYYY-MM-DD');
    var amonthago = moment().add(-30,"days").format('YYYY-MM-DD');

    var day_feed_chart_type = null;

    var day_his_chart = null;
    var hour_his_chart = null;

    var selectedTreeNode=null;
    var pig_num_total = 0;
    var house_type=0;
    var housename='';
    var farmname = '';
    var area_name = '';
    var group_name = '';
    var cur_selected_item = null;

    var calFeedErr = false;
    var dfxw_unit_day_age = -127;
    var dfxw_unit_num = -127;
    var linkage_feed = 0;//联动水料比
    var dfxw_id = 0;

    console.info(getByteBit("3",1));
    

    var tree_setting = {
        async: {
            enable: true,
            type: "get",
            headers:{'Authorization':token},
            url: '../Api/Topo/GetAsync',
            autoParam:["id", "type"], //节点参数提交给后台,这里提交id和类型到后台
            otherParam:{"device_type":"DMXFGW"}, //静态参数
            dataFilter: filter,
        },
        view: {
            dblClickExpand: false,
            fontCss: getFont,
            nameIsHTML: true,
        },
        callback: {
            onClick: treeOnClick,
        }
    };
    function filter(treeId, parentNode, res) {
        console.info(res)
        if (!res.data) return null;
        var nodes = res.data;
        nodes=setDataIcon(nodes);
        return nodes;
    }


    var day_his_chart_options = {
        // backgroundColor:'#0e1a39',
        legend: {
            show:true,
            x:'center',
            y:'10',
            icon: 'stack',
            itemWidth:10,
            itemHeight:10,
            textStyle: {
                fontSize: 11,
                color: titleColor
            },
            data:[{name:'头均实际采食(kg)',icon:'rect'},{name:"低采食预警(kg)",icon:'circle'},{name:"标准采食(kg)",icon:'circle'}]
        },
        toolbox: {
            show: true,
            right:10,
            itemSize:12,
            iconStyle:{
                //color:'#ffffff',
            },
            feature: {
                saveAsImage: {
                    title: '保存图片',
                },
                myExport: {
                    show: true,
                    title: '导出Excel',
                    icon: 'path://M832 1024H192a64 64 0 0 1-64-64V64a64 64 0 0 1 64-64h448v3.968L896 256v704a64 64 0 0 1-64 64zM640 127.488V256h129.472L640 127.488zM832 320h-192a64 64 0 0 1-64-64V64H192v896h640V320z',
                    onclick: function (){
                        onExportDayFeed();
                    }
                }
            }
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                lineStyle: {
                    color: '#ffffff'
                },
            }
        },
        grid: {
            top: '20%',
            left: '5%',
            right: '5%',
            bottom: '15%',
            containLabel: true
        },
        xAxis: [{
            type: 'category',
            axisLine: {
                show: true
            },
            splitArea: {
                // show: true,
                color: '#f00',
                lineStyle: {
                    color: '#f00'
                },
            },
            axisLabel: {
                color: titleColor
            },
            splitLine: {
                show: false
            },
            boundaryGap: false,
            //data: ['A', 'B', 'C', 'D', 'E', 'F'],

        }],
        yAxis: [{
            type: 'value',
            min: 0,
            max: function (value) {
                return value.max + 1;
            },
            splitLine: {
                show: false,
                lineStyle: {
                    color: 'rgba(255,255,255,0.1)'
                }
            },
            axisLine: {
                show: false,
            },
            axisLabel: {
                show: true,
                margin: 20,
                textStyle: {
                    color: titleColor,

                },
            },
            axisTick: {
                show: true,
            },
        },{
            type: 'value',
            min: 0,
            max: function (value) {
                return value.max + 1;
            },
            splitLine: {
                show: true,
                lineStyle: {
                    color: 'rgba(255,255,255,0.1)'
                }
            },
            axisLine: {
                show: false,
            },
            axisLabel: {
                show: true,
                margin: 20,
                textStyle: {
                    color: titleColor,

                },
            },
            axisTick: {
                show: true,
            },
        },{
            type: 'value',
            min: 0,
            max: function (value) {
                return value.max + 1;
            },
            splitLine: {
                show: true,
                lineStyle: {
                    color: 'rgba(255,255,255,0.1)'
                }
            },
            axisLine: {
                show: false,
            },
            axisLabel: {
                show: true,
                margin: 20,
                textStyle: {
                    color: titleColor,

                },
            },
            axisTick: {
                show: true,
            },
        }],
        series: [{
                name: '头均实际采食(kg)',
                type: 'bar',
                //barWidth: '10px',
                barMaxWidth:'10px',
                yAxisIndex: 1,
                data: [],
                itemStyle: {
                    normal: {
                        color: green,
                        // barBorderRadius: [30, 30, 30, 30],
                        // shadowColor: '#f29725',
                        // shadowBlur: 4,
                    }
                },
                tooltip: {
                    show: true
                }
            }
            ,{
                name: '低采食预警(kg)',
                type: 'line',
                smooth: false, //是否平滑
                showSymbol: true,
                yAxisIndex: 1,
                itemStyle: {
                    normal: {
                        color: lightOrangeColor1,
                        lineStyle: {
                            width: 1,
                            type: 'solid' //'dotted'虚线 'solid'实线
                        },
                        borderColor: lightOrangeColor1, //图形的描边颜色。支持的格式同 color
                        //borderWidth: 8 ,//描边线宽。为 0 时无描边。[ default: 0 ]
                        barBorderRadius: 0,
                        label: {
                            show: false,
                        },
                        opacity:0.5,
                    }
                },
                tooltip: {
                    show: true
                }
            }
            ,{
                name: '标准采食(kg)',
                type: 'line',
                smooth: false, //是否平滑
                showSymbol: true,
                yAxisIndex: 1,
                itemStyle: {
                    normal: {
                        color: blue,
                        lineStyle: {
                            width: 1,
                            type: 'solid' //'dotted'虚线 'solid'实线
                        },
                        borderColor: blue, //图形的描边颜色。支持的格式同 color
                        //borderWidth: 8 ,//描边线宽。为 0 时无描边。[ default: 0 ]
                        barBorderRadius: 0,
                        label: {
                            show: false,
                        },
                        opacity:0.5,
                    }
                },
                tooltip: {
                    show: true
                }
            }
        ]
    };

    var hour_his_chart_options = {
        // backgroundColor:'#0e1a39',
        legend: {
            show:true,
            x:'center',
            y:'10',
            icon: 'stack',
            itemWidth:10,
            itemHeight:10,
            textStyle: {
                fontSize: 11,
                color: titleColor
            },
            data:[{name:'小时总下料量(kg)',icon:'rect'},{name:'小时总下水量(L)',icon:'rect'},{name:"小时头均下料量(kg)",icon:'circle'}]
        },
        toolbox: {
            show: true,
            right:10,
            itemSize:12,
            iconStyle:{
                //color:'#ffffff',
            },
            feature: {
                saveAsImage: {
                    title: '保存图片',
                },
                myExport: {
                    show: true,
                    title: '导出Excel',
                    icon: 'path://M832 1024H192a64 64 0 0 1-64-64V64a64 64 0 0 1 64-64h448v3.968L896 256v704a64 64 0 0 1-64 64zM640 127.488V256h129.472L640 127.488zM832 320h-192a64 64 0 0 1-64-64V64H192v896h640V320z',
                    onclick: function (){
                        onExportHourFeed();
                    }
                }
            }
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                lineStyle: {
                    color: {
                        type: 'linear',
                        x: 0,
                        y: 0,
                        x2: 0,
                        y2: 1,
                        colorStops: [{
                            offset: 0,
                            color: 'rgba(0, 255, 233,0)'
                        }, {
                            offset: 0.5,
                            color: 'rgba(255, 255, 255,1)',
                        }, {
                            offset: 1,
                            color: 'rgba(0, 255, 233,0)'
                        }],
                        global: false
                    }
                },
            }
        },
        
        grid: {
            top: '20%',
            left: '5%',
            right: '5%',
            bottom: '15%',
            containLabel: true
        },
        xAxis: [{
            type: 'category',
            axisLine: {
                show: true
            },
            splitArea: {
                // show: true,
                color: '#f00',
                lineStyle: {
                    color: '#f00'
                },
            },
            axisLabel: {
                color: titleColor
            },
            splitLine: {
                show: false
            },
            boundaryGap: false,
            //data: ['A', 'B', 'C', 'D', 'E', 'F'],

        }],
        yAxis: [{
            type: 'value',
            min: 0,
            max: function (value) {
                return value.max + 1;
            },
            splitLine: {
                show: false,
                lineStyle: {
                    color: 'rgba(255,255,255,0.1)'
                }
            },
            axisLine: {
                show: false,
            },
            axisLabel: {
                show: true,
                margin: 20,
                textStyle: {
                    color: titleColor,

                },
            },
            axisTick: {
                show: true,
            },
        },{
            type: 'value',
            min: 0,
            max: function (value) {
                return value.max + 1;
            },
            splitLine: {
                show: true,
                lineStyle: {
                    color: 'rgba(255,255,255,0.1)'
                }
            },
            axisLine: {
                show: false,
            },
            axisLabel: {
                show: true,
                margin: 20,
                textStyle: {
                    color: titleColor,

                },
            },
            axisTick: {
                show: true,
            },
        }],
        series: [{
                name: '小时总下料量(kg)',
                type: 'bar',
                //barWidth: '10px',
                barMaxWidth:'5px',
                yAxisIndex: 1,
                data: [],
                itemStyle: {
                    normal: {
                        color: nanmu_green,
                        // barBorderRadius: [30, 30, 30, 30],
                        // shadowColor: '#f29725',
                        // shadowBlur: 4,
                    }
                },
                tooltip: {
                    show: true
                }
            },{
                name: '小时总下水量(L)',
                type: 'bar',
                //barWidth: '10px',
                barMaxWidth:'5px',
                yAxisIndex: 1,
                data: [],
                itemStyle: {
                    normal: {
                        color: blue,
                        // barBorderRadius: [30, 30, 30, 30],
                        // shadowColor: '#f29725',
                        // shadowBlur: 4,
                    }
                },
                tooltip: {
                    show: true
                }
            }
            ,{
                name: '小时头均下料量(kg)',
                type: 'line',
                smooth: false, //是否平滑
                showSymbol: true,
                yAxisIndex: 1,
                itemStyle: {
                    normal: {
                        color: lightOrangeColor1,
                        lineStyle: {
                            width: 1,
                            type: 'dotted' //'dotted'虚线 'solid'实线
                        },
                        borderColor: lightOrangeColor1, //图形的描边颜色。支持的格式同 color
                        //borderWidth: 8 ,//描边线宽。为 0 时无描边。[ default: 0 ]
                        barBorderRadius: 0,
                        label: {
                            show: false,
                        },
                        opacity:0.5,
                    }
                },
                tooltip: {
                    show: true
                }
            }
        ]
    };

    layui.config({
        base: '../layuiadmin/' //静态资源所在路径
    }).extend({
        index: 'lib/index' //主入口模块
    }).use(['index','layer','form', 'table','transfer','laydate','element','dropdown'],function(){
        form = layui.form;
        table = layui.table;
        transfer = layui.transfer;
        laydate = layui.laydate;
        element = layui.element;
        dropdown = layui.dropdown;

        toastr.options = {
            "closeButton": false, //是否显示关闭按钮
            "debug": false, //是否使用debug模式
            "positionClass": "toast-top-center",//弹出窗的位置
            "showDuration": "300",//显示的动画时间
            "hideDuration": "1000",//消失的动画时间
            "timeOut": "2000", //展现时间
            "extendedTimeOut": "1000",//加长展示时间
            "showEasing": "swing",//显示时的动画缓冲方式
            "hideEasing": "linear",//消失时的动画缓冲方式
            "showMethod": "fadeIn",//显示时的动画方式
            "hideMethod": "fadeOut" //消失时的动画方式
        };

        form.verify({
            verify_ip:verify_ip,
            addr: function(value, item){ //value：表单的值、item：表单的DOM对象
                if(/^\d+\d+\d$/.test(value)==false){
                    return '必须是10进制数值';
                }
                if(value.length!==10){
                    return '长度必须是10';
                }
            },
            percent: function(value, item){ //value：表单的值、item：表单的DOM对象
                if(/^([0-9]{1,2}|100)$/.test(value)==false){
                    return '0-100之间的正整数';
                }
            },
        });



        $.ajax({
            type: 'GET',
            url: '../Api/User/Actions',
            data: {func_url:func_url},
            beforeSend: function(request) {
                request.setRequestHeader("Authorization", 'Bearer '+window.localStorage.getItem("token"));
            },
            dataType: "json",
            success: function (data) {
                console.info(data)
                actions=data.data;
                for(var i=0;i<actions.length;i++){
                    $('.action-'+actions[i].action_id).removeClass("layui-hide");
                }
                
                if(group_code=='sbt' || is_admin>0 || role_ids=='service'){
                    $("#btn_set_waterPTTO").show();
                }else{
                    $("#btn_set_waterPTTO").hide();
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                layer.msg('加载操作信息失败');
            }
        });

        $.ajax({
            type: 'GET',
            url:"/Api/Dictionary",
            data: {code:"SYS_PIG_TYPE"},
            beforeSend: function(request) {
                request.setRequestHeader("Authorization", 'Bearer '+window.localStorage.getItem("token"));
            },
            success: function(data){
                if(data){
                    var list=data.data;
                    console.info(list);
                    SYS_PIG_TYPE=list;
                }
            },
            complete: function(XMLHttpRequest, textStatus) {
                //layer.closeAll('loading');
            },
            dataType: "json"
        });


        //监听提交
        form.on('submit(btn_search)', function(data){
            console.info(data.field);
            search(data.field);
            return false;
        });
        form.on('submit(btn_refresh)', function(data){
            $("#btn_search").click();
            return false;
        });

        form.on('submit(btn_search_plan)', function(data){
            console.info(data.field);
            searchPlan(data.field);
            return false;
        });

        form.on('select(group_code)', function(data){
            var group_code=data.value;
            console.info("group_code",group_code);
            renderFarmSelect(group_code);
        });
        //批量设置参数
        form.on('submit(btn_apply_plan)', function(data){

            var checkStatus = table.checkStatus('table'); //idTest 即为基础参数 id 对应的值

            var checkData = checkStatus.data;
            console.log("checkData",checkData); //获取选中行的数据
            if(checkData.length==0){
                toastr.warning("请勾选需要批量设置的饲喂器");
            }else{

                var feedNum = 0;
                var fgNum = 0;
                for(var i=0;i<checkData.length;i++)
                {
                    var model = checkData[i].model;
                    if(model=="feed"){
                        feedNum++;
                    }
                    if(model=="fg"){
                        fgNum++;
                    }
                    
                }

                
                if(feedNum>0 && fgNum>0){
                    toastr.warning("不能选择多种设备下发方案");
                    return false;
                }
                if(feedNum>0 && fgNum==0){
                    node_model = "feed";
                }
                if(fgNum>0 && feedNum==0){
                    node_model = "fg";
                }
                console.info(feedNum,fgNum,node_model);
                //return ;

                $("#plan_key").val("");

                //弹出选择方案
                layer.open({
                    //area: 'auto',
                    area:['80%','600px'],
                    //offset: '50px',
                    shade: 0.5,
                    shadeClose: true,
                    type: 1,
                    title: '选择方案', //不显示标题
                    content: $('#form_plan'), //捕获的元素，注意：最好该指定的元素要存放在body最外层，否则可能被其它的相对元素所影响
                    maxmin: false,
                    btn: ['启动', '关闭'],
                    yes: function(index, layero){
                        //点击确认触发 iframe 内容中的按钮提交
                        lay_index=index;
                        //应用方案
                        var checkStatus = table.checkStatus('table_plan'); //idTest 即为基础参数 id 对应的值
                        var checkPlanData = checkStatus.data;
                        //console.log(checkPlanData); //获取选中行的数据
                        if(checkPlanData.length==0){
                            toastr.warning("请先勾选方案");
                        }else{
                            //return;
                            nodeParaArr=[];
                            addrArr=[];
                            enableArr=[];
                            tnArr=[];
                            //console.info(checkData);
                            
                            for(var i=0;i<checkData.length;i++){
                                var nodePara = JSON.parse(checkData[i].para);
                                
                                
                                
                                //console.info(nodePara);
                                nodeParaArr.push(nodePara);
                                addrArr.push(checkData[i].addr);
                                enableArr.push(checkData[i].enable);
                                tnArr.push(checkData[i].tn);
                            }

                            var plan = checkPlanData[0];
                            var planPara = JSON.parse(plan.para);

                            //console.info(nodeParaArr);
                            //console.info(addrArr);
                            //console.info(enableArr);
                            //console.info(tnArr);
                            //console.info(planPara);

                            
                            //应用方案参数
                            for(var i=0;i<nodeParaArr.length;i++){
                                if(planPara){
                                    //console.info("旧",nodeParaArr[i]);

                                    var Sn = nodeParaArr[i].Sn;
                                    var Passwd = nodeParaArr[i].Passwd;
                                    var Gday = nodeParaArr[i].Gday;
                                    var Hnum = nodeParaArr[i].Hnum;
                                    //var CalFeed = nodeParaArr[i].CalFeed;

                                    nodeParaArr[i] =JSON.parse(JSON.stringify(planPara));
                                    nodeParaArr[i].Sn = Sn;
                                    nodeParaArr[i].Passwd = Passwd;
                                    nodeParaArr[i].Gday = Gday;
                                    nodeParaArr[i].Hnum = Hnum;
                                    //nodeParaArr[i].CalFeed = CalFeed;
                                    
                                    //console.info("新",nodeParaArr[i]);
                                }
                            }
                            console.info(nodeParaArr);

                            layer.confirm('确认对勾选的'+nodeParaArr.length.toString()+"个饲喂器使用方案:["+plan.name+"]设置?", function(index){
                                layer.close(index); //再执行关闭
                                progress_index = layer.open({
                                    //area: 'auto',
                                    area:['400px','200px'],
                                    type: 1,
                                    shade: 0.3,
                                    title: '下发参数中', //不显示标题
                                    btn: ['终止'],
                                    content: $('#form-progress'), //捕获的元素，注意：最好该指定的元素要存放在body最外层，否则可能被其它的相对元素所影响
                                    yes: function(index, layero){
                                        layer.close(progress_index);
                                        apply_run =false;
                                        toastr.warning("已经终止");
                                    }
                                });

                                element.progress('progress', "0%");
                                apply_idx = 0;
                                apply_run =true;
                                apply_retry = 0;
                                apply_failed_idx_arr=[];
                                feed_plan_id = plan.id;
                                loopSetNodeParam();
                            });
                        }
                    }
                });

                //加载方案列表
                showPlanTable();
            }
            return false;
        });

        //分娩
        form.on('submit(btn_born)', function(data){
            var checkStatus = table.checkStatus('table'); //idTest 即为基础参数 id 对应的值

            var checkData = checkStatus.data;
            console.log(checkData); //获取选中行的数据
            if(checkData.length==0){
                toastr.warning("请勾选需要批量设置的饲喂器");
            }else{
                nodeParaArr=[];
                addrArr=[];
                enableArr=[];
                tnArr=[];
                for(var i=0;i<checkData.length;i++){
                    var nodePara = JSON.parse(checkData[i].para);
                    nodeParaArr.push(nodePara);
                    addrArr.push(checkData[i].addr);
                    enableArr.push(checkData[i].enable);
                    tnArr.push(checkData[i].tn);
                }

                //应用方案参数
                for(var i=0;i<nodeParaArr.length;i++){
                    //应用参数字段
                    nodeParaArr[i].Mode = EMODE_LACTATION_NEW.toString();
                    nodeParaArr[i].Gday = "1";

                }

                layer.confirm('确认对勾选的'+nodeParaArr.length.toString()+"个饲喂器 一键分娩?", function(index){
                    layer.close(index); //再执行关闭
                    progress_index = layer.open({
                        //area: 'auto',
                        area:['400px','200px'],
                        type: 1,
                        shade: 0.3,
                        title: '设置', //不显示标题
                        btn: ['终止'],
                        content: $('#form-progress'), //捕获的元素，注意：最好该指定的元素要存放在body最外层，否则可能被其它的相对元素所影响
                        yes: function(index, layero){
                            layer.close(progress_index);
                            apply_run =false;
                            toastr.warning("已经终止");
                        }
                    });

                    element.progress('progress', "0%");
                    apply_idx = 0;
                    apply_run =true;
                    apply_retry = 0;
                    apply_failed_idx_arr=[];
                    loopSetNodeParam();
                });
            }
            return false;
        });

        //设置栏位 btn_set_hnum
        form.on('submit(btn_set_hnum)', function(data){
            var checkStatus = table.checkStatus('table'); //idTest 即为基础参数 id 对应的值

            var checkData = checkStatus.data;
            console.log(checkData); //获取选中行的数据
            if(checkData.length==0){
                toastr.warning("请勾选需要批量设置的饲喂器");
            }else{
                nodeParaArr=[];
                addrArr=[];
                enableArr=[];
                tnArr=[];
                hnumArr=[];
                for(var i=0;i<checkData.length;i++){
                    var nodePara = JSON.parse(checkData[i].para);
                    nodeParaArr.push(nodePara);
                    addrArr.push(checkData[i].addr);
                    enableArr.push(checkData[i].enable);
                    tnArr.push(checkData[i].tn);
                    hnumArr.push(checkData[i].hnum);
                }

                layer.confirm('确认对勾选的'+nodeParaArr.length.toString()+"个饲喂器 下发栏位号?", function(index){
                    layer.close(index); //再执行关闭
                    progress_index = layer.open({
                        //area: 'auto',
                        area:['400px','200px'],
                        type: 1,
                        shade: 0.3,
                        title: '设置', //不显示标题
                        btn: ['终止'],
                        content: $('#form-progress'), //捕获的元素，注意：最好该指定的元素要存放在body最外层，否则可能被其它的相对元素所影响
                        yes: function(index, layero){
                            layer.close(progress_index);
                            apply_run =false;
                            toastr.warning("已经终止");
                        }
                    });

                    element.progress('progress', "0%");
                    apply_idx = 0;
                    apply_run =true;
                    apply_retry = 0;
                    apply_failed_idx_arr=[];
                    loopSetNodeHnum();
                });
            }
            return false;
        });


        //设置日龄
        form.on('submit(btn_set_day)', function(data){
            var checkStatus = table.checkStatus('table'); //idTest 即为基础参数 id 对应的值

            var checkData = checkStatus.data;
            console.log(checkData); //获取选中行的数据
            if(checkData.length==0){
                toastr.warning("请勾选需要批量设置的饲喂器");
            }else{
                form.val("form_set_day",{day:checkData[0]["day"]});
                layer.open({
                    //area: 'auto',
                    area:['300px','250px'],
                    type: 1,
                    shade: 0.3,
                    offset: '15%',
                    shadeClose:true,
                    title: '设置日龄', //不显示标题
                    content: $('#form_set_day'), //捕获的元素，注意：最好该指定的元素要存放在body最外层，否则可能被其它的相对元素所影响
                    btn: ['确定', '取消']
                    ,yes: function(index, layero){
                        lay_index=index;
                        var submit = layero.find("#on_btn_set_day");
                        submit.click();
                    }
                });
            }
            return false;
        });
        form.on('submit(on_btn_set_day)', function(data){
            var checkStatus = table.checkStatus('table'); //idTest 即为基础参数 id 对应的值

            var checkData = checkStatus.data;
            console.log(checkData); //获取选中行的数据
            if(checkData.length==0){
                toastr.warning("请勾选需要批量设置的饲喂器");
            }else{
                var obj = form.val("form_set_day");
                set_day = obj.day;
                if(set_day==""){
                    toastr.warning("日龄不能为空");
                    return false;
                }else{
                    set_day = parseInt(set_day);
                    if(set_day<=0){
                        toastr.warning("日龄必须大于0");
                        return false;
                    }
                }

                nodeParaArr=[];
                addrArr=[];
                enableArr=[];
                tnArr=[];
                for(var i=0;i<checkData.length;i++){
                    var nodePara = JSON.parse(checkData[i].para);
                    nodeParaArr.push(nodePara);
                    addrArr.push(checkData[i].addr);
                    enableArr.push(checkData[i].enable);
                    tnArr.push(checkData[i].tn);
                }

                

                layer.confirm('确认对勾选的'+nodeParaArr.length.toString()+"个饲喂器 设置日龄为:["+set_day+"]?", function(index){
                    layer.close(index); //再执行关闭
                    progress_index = layer.open({
                        //area: 'auto',
                        area:['400px','200px'],
                        type: 1,
                        shade: 0.3,
                        title: '设置', //不显示标题
                        btn: ['终止'],
                        content: $('#form-progress'), //捕获的元素，注意：最好该指定的元素要存放在body最外层，否则可能被其它的相对元素所影响
                        yes: function(index, layero){
                            layer.close(progress_index);
                            apply_run =false;
                            toastr.warning("已经终止");
                        }
                    });

                    element.progress('progress', "0%");
                    apply_idx = 0;
                    apply_run =true;
                    apply_retry = 0;
                    apply_failed_idx_arr=[];
                    loopSetNodeDay();
                });

            }
            return false;
        });

        //远程下料下水
        form.on('submit(btn_remoteFeed)', function(data){
            var checkStatus = table.checkStatus('table'); //idTest 即为基础参数 id 对应的值

            var checkData = checkStatus.data;
            console.log(checkData); //获取选中行的数据
            if(checkData.length==0){
                toastr.warning("请勾选需要批量下水/料的饲喂器");
            }else{
                form.val("form_manul",{water:'100',feed:'100'});
                layer.open({
                    //area: 'auto',
                    area:['350px','350px'],
                    type: 1,
                    shade: 0.3,
                    offset: '15%',
                    shadeClose:true,
                    title: '远程下水下料', //不显示标题
                    content: $('#form_manul'), //捕获的元素，注意：最好该指定的元素要存放在body最外层，否则可能被其它的相对元素所影响
                    btn: ['确定', '取消']
                    ,yes: function(index, layero){
                        lay_index=index;
                        var submit = layero.find("#on_btn_manul_batch");
                        submit.click();
                    }
                });
            }
            return false;
        });
        form.on('submit(on_btn_manul_batch)', function(data){
            var checkStatus = table.checkStatus('table'); //idTest 即为基础参数 id 对应的值

            var checkData = checkStatus.data;
            console.log(checkData); //获取选中行的数据
            if(checkData.length==0){
                toastr.warning("请勾选需要批量下水料的饲喂器");
            }else{
                var obj = form.val("form_manul");
                set_water = obj.water;
                set_feed = obj.feed;

                nodeParaArr=[];
                addrArr=[];
                enableArr=[];
                tnArr=[];
                for(var i=0;i<checkData.length;i++){
                    var nodePara = JSON.parse(checkData[i].para);
                    nodeParaArr.push(nodePara);
                    addrArr.push(checkData[i].addr);
                    enableArr.push(checkData[i].enable);
                    tnArr.push(checkData[i].tn);
                }

                

                layer.confirm('确认对勾选的'+nodeParaArr.length.toString()+"个饲喂器 下水:["+set_water+" ml],下料:["+set_feed+" g]?", function(index){
                    layer.close(index); //再执行关闭
                    progress_index = layer.open({
                        //area: 'auto',
                        area:['400px','200px'],
                        type: 1,
                        shade: 0.3,
                        title: '设置', //不显示标题
                        btn: ['终止'],
                        content: $('#form-progress'), //捕获的元素，注意：最好该指定的元素要存放在body最外层，否则可能被其它的相对元素所影响
                        yes: function(index, layero){
                            layer.close(progress_index);
                            apply_run =false;
                            toastr.warning("已经终止");
                        }
                    });

                    element.progress('progress', "0%");
                    apply_idx = 0;
                    apply_run =true;
                    apply_retry = 0;
                    apply_failed_idx_arr=[];
                    loopSetNodeFeedWater();
                });

            }
            return false;
        });


        //校准AD
        form.on('submit(btn_set_calAD)', function(data){
            var checkStatus = table.checkStatus('table'); //idTest 即为基础参数 id 对应的值

            var checkData = checkStatus.data;
            console.log(checkData); //获取选中行的数据
            
            if(checkData.length==0){
                toastr.warning("请勾选需要批量设置的饲喂器");
            }else{
                var para = JSON.parse(checkData[0]['para']);
                console.log(para);
                form.val("form_set_calAD",{calAD:para["CalAD"],calADR:para["CalADR"]});
                layer.open({
                    //area: 'auto',
                    area:['400px','250px'],
                    type: 1,
                    shade: 0.3,
                    offset: '15%',
                    shadeClose:true,
                    title: '设置校水值', //不显示标题
                    content: $('#form_set_calAD'), //捕获的元素，注意：最好该指定的元素要存放在body最外层，否则可能被其它的相对元素所影响
                    btn: ['确定', '取消']
                    ,yes: function(index, layero){
                        lay_index=index;
                        var submit = layero.find("#on_btn_set_calAD");
                        submit.click();
                    }
                });
            }
            return false;
        });
        form.on('submit(on_btn_set_calAD)', function(data){
            var checkStatus = table.checkStatus('table'); //idTest 即为基础参数 id 对应的值

            var checkData = checkStatus.data;
            console.log(checkData); //获取选中行的数据
            if(checkData.length==0){
                toastr.warning("请勾选需要批量设置的饲喂器");
            }else{
                var obj = form.val("form_set_calAD");
                set_calAD = obj.calAD;
                set_calADR = obj.calADR;

                nodeParaArr=[];
                addrArr=[];
                enableArr=[];
                tnArr=[];
                for(var i=0;i<checkData.length;i++){
                    var nodePara = JSON.parse(checkData[i].para);
                    nodeParaArr.push(nodePara);
                    addrArr.push(checkData[i].addr);
                    enableArr.push(checkData[i].enable);
                    tnArr.push(checkData[i].tn);
                }

                

                layer.confirm('确认对勾选的'+nodeParaArr.length.toString()+"个饲喂器 设置SSD值?", function(index){
                    layer.close(index); //再执行关闭
                    progress_index = layer.open({
                        //area: 'auto',
                        area:['400px','200px'],
                        type: 1,
                        shade: 0.3,
                        title: '设置', //不显示标题
                        btn: ['终止'],
                        content: $('#form-progress'), //捕获的元素，注意：最好该指定的元素要存放在body最外层，否则可能被其它的相对元素所影响
                        yes: function(index, layero){
                            layer.close(progress_index);
                            apply_run =false;
                            toastr.warning("已经终止");
                        }
                    });

                    element.progress('progress', "0%");
                    apply_idx = 0;
                    apply_run =true;
                    apply_retry = 0;
                    apply_failed_idx_arr=[];
                    loopSetNodeCalAD();
                });

            }
            return false;
        });

        //设置水压 btn_set_waterPTTO
        form.on('submit(btn_set_waterPTTO)', function(data){
            var checkStatus = table.checkStatus('table'); //idTest 即为基础参数 id 对应的值

            var checkData = checkStatus.data;
            console.log(checkData); //获取选中行的数据
            
            if(checkData.length==0){
                toastr.warning("请勾选需要批量设置的饲喂器");
            }else{
                var para = JSON.parse(checkData[0]['para']);
                console.log(para);
                form.val("form_set_waterPTTO",{waterPTTO:para["WaterPTTO"]});
                layer.open({
                    //area: 'auto',
                    area:['400px','250px'],
                    type: 1,
                    shade: 0.3,
                    offset: '15%',
                    shadeClose:true,
                    title: '设置水压', //不显示标题
                    content: $('#form_set_waterPTTO'), //捕获的元素，注意：最好该指定的元素要存放在body最外层，否则可能被其它的相对元素所影响
                    btn: ['确定', '取消']
                    ,yes: function(index, layero){
                        lay_index=index;
                        var submit = layero.find("#on_btn_set_waterPTTO");
                        submit.click();
                    }
                });
            }
            return false;
        });
        form.on('submit(on_btn_set_waterPTTO)', function(data){
            var checkStatus = table.checkStatus('table'); //idTest 即为基础参数 id 对应的值

            var checkData = checkStatus.data;
            console.log(checkData); //获取选中行的数据
            if(checkData.length==0){
                toastr.warning("请勾选需要批量设置的饲喂器");
            }else{
                var obj = form.val("form_set_waterPTTO");
                set_waterPTTO = obj.waterPTTO;

                nodeParaArr=[];
                addrArr=[];
                enableArr=[];
                tnArr=[];
                for(var i=0;i<checkData.length;i++){
                    var nodePara = JSON.parse(checkData[i].para);
                    nodeParaArr.push(nodePara);
                    addrArr.push(checkData[i].addr);
                    enableArr.push(checkData[i].enable);
                    tnArr.push(checkData[i].tn);
                }

                

                layer.confirm('确认对勾选的'+nodeParaArr.length.toString()+"个饲喂器 设置水压值?", function(index){
                    layer.close(index); //再执行关闭
                    progress_index = layer.open({
                        //area: 'auto',
                        area:['400px','200px'],
                        type: 1,
                        shade: 0.3,
                        title: '设置', //不显示标题
                        btn: ['终止'],
                        content: $('#form-progress'), //捕获的元素，注意：最好该指定的元素要存放在body最外层，否则可能被其它的相对元素所影响
                        yes: function(index, layero){
                            layer.close(progress_index);
                            apply_run =false;
                            toastr.warning("已经终止");
                        }
                    });

                    element.progress('progress', "0%");
                    apply_idx = 0;
                    apply_run =true;
                    apply_retry = 0;
                    apply_failed_idx_arr=[];
                    loopSetNodeWaterPTTO();
                });

            }
            return false;
        });
        
        //校准AD
        form.on('submit(btn_set_calAD)', function(data){
            var checkStatus = table.checkStatus('table'); //idTest 即为基础参数 id 对应的值

            var checkData = checkStatus.data;
            console.log(checkData); //获取选中行的数据
            
            if(checkData.length==0){
                toastr.warning("请勾选需要批量设置的饲喂器");
            }else{
                var para = JSON.parse(checkData[0]['para']);
                console.log(para);
                form.val("form_set_calAD",{calAD:para["CalAD"],calADR:para["CalADR"]});
                layer.open({
                    //area: 'auto',
                    area:['400px','250px'],
                    type: 1,
                    shade: 0.3,
                    offset: '15%',
                    shadeClose:true,
                    title: '设置校水值', //不显示标题
                    content: $('#form_set_calAD'), //捕获的元素，注意：最好该指定的元素要存放在body最外层，否则可能被其它的相对元素所影响
                    btn: ['确定', '取消']
                    ,yes: function(index, layero){
                        lay_index=index;
                        var submit = layero.find("#on_btn_set_calAD");
                        submit.click();
                    }
                });
            }
            return false;
        });

        //下料校准 btn_set_calFeed
        form.on('submit(btn_set_calFeed)', function(data){
            var checkStatus = table.checkStatus('table'); //idTest 即为基础参数 id 对应的值

            var checkData = checkStatus.data;
            console.log(checkData); //获取选中行的数据
            
            if(checkData.length==0){
                toastr.warning("请勾选需要批量设置的饲喂器");
            }else{
                var para = JSON.parse(checkData[0]['para']);
                console.log(para);
                form.val("form_set_calFeed",{calFeed:para["CalFeed"]});
                layer.open({
                    //area: 'auto',
                    area:['400px','250px'],
                    type: 1,
                    shade: 0.3,
                    offset: '15%',
                    shadeClose:true,
                    title: '设置下料校准', //不显示标题
                    content: $('#form_set_calFeed'), //捕获的元素，注意：最好该指定的元素要存放在body最外层，否则可能被其它的相对元素所影响
                    btn: ['确定', '取消']
                    ,yes: function(index, layero){
                        lay_index=index;
                        var submit = layero.find("#on_btn_set_calFeed");
                        submit.click();
                    }
                });
            }
            return false;
        });

        form.on('submit(on_btn_set_calFeed)', function(data){
            var checkStatus = table.checkStatus('table'); //idTest 即为基础参数 id 对应的值

            var checkData = checkStatus.data;
            console.log(checkData); //获取选中行的数据
            if(checkData.length==0){
                toastr.warning("请勾选需要批量设置的饲喂器");
            }else{
                var obj = form.val("form_set_calFeed");
                set_calFeed = obj.calFeed;

                nodeParaArr=[];
                addrArr=[];
                enableArr=[];
                tnArr=[];
                for(var i=0;i<checkData.length;i++){
                    var nodePara = JSON.parse(checkData[i].para);
                    nodeParaArr.push(nodePara);
                    addrArr.push(checkData[i].addr);
                    enableArr.push(checkData[i].enable);
                    tnArr.push(checkData[i].tn);
                }

                

                layer.confirm('确认对勾选的'+nodeParaArr.length.toString()+"个饲喂器 设置10圈出料数为:["+set_calFeed+"]?", function(index){
                    layer.close(index); //再执行关闭
                    progress_index = layer.open({
                        //area: 'auto',
                        area:['400px','200px'],
                        type: 1,
                        shade: 0.3,
                        title: '设置', //不显示标题
                        btn: ['终止'],
                        content: $('#form-progress'), //捕获的元素，注意：最好该指定的元素要存放在body最外层，否则可能被其它的相对元素所影响
                        yes: function(index, layero){
                            layer.close(progress_index);
                            apply_run =false;
                            toastr.warning("已经终止");
                        }
                    });

                    element.progress('progress', "0%");
                    apply_idx = 0;
                    apply_run =true;
                    apply_retry = 0;
                    apply_failed_idx_arr=[];
                    loopSetNodeCalFeed();
                });

            }
            return false;
        });

        //设置水阀
        form.on('submit(btn_set_pulseWater)', function(data){
            var checkStatus = table.checkStatus('table'); //idTest 即为基础参数 id 对应的值

            var checkData = checkStatus.data;
            console.log(checkData); //获取选中行的数据
            
            if(checkData.length==0){
                toastr.warning("请勾选需要批量设置的饲喂器");
            }else{
                var para = JSON.parse(checkData[0]['para']);
                console.log(para);
                form.val("form_set_pulseWater",{pulseWater:para["PulseWater"]});
                layer.open({
                    //area: 'auto',
                    area:['400px','250px'],
                    type: 1,
                    shade: 0.3,
                    offset: '15%',
                    shadeClose:true,
                    title: '设置水阀', //不显示标题
                    content: $('#form_set_pulseWater'), //捕获的元素，注意：最好该指定的元素要存放在body最外层，否则可能被其它的相对元素所影响
                    btn: ['确定', '取消']
                    ,yes: function(index, layero){
                        lay_index=index;
                        var submit = layero.find("#on_btn_set_pulseWater");
                        submit.click();
                    }
                });
            }
            return false;
        });
        form.on('submit(on_btn_set_pulseWater)', function(data){
            var checkStatus = table.checkStatus('table'); //idTest 即为基础参数 id 对应的值

            var checkData = checkStatus.data;
            console.log(checkData); //获取选中行的数据
            if(checkData.length==0){
                toastr.warning("请勾选需要批量设置的饲喂器");
            }else{
                var obj = form.val("form_set_pulseWater");
                set_pulseWater = obj.pulseWater;

                nodeParaArr=[];
                addrArr=[];
                enableArr=[];
                tnArr=[];
                for(var i=0;i<checkData.length;i++){
                    var nodePara = JSON.parse(checkData[i].para);
                    nodeParaArr.push(nodePara);
                    addrArr.push(checkData[i].addr);
                    enableArr.push(checkData[i].enable);
                    tnArr.push(checkData[i].tn);
                }

                

                layer.confirm('确认对勾选的'+nodeParaArr.length.toString()+"个饲喂器 设置为:["+set_pulseWater+"]?", function(index){
                    layer.close(index); //再执行关闭
                    progress_index = layer.open({
                        //area: 'auto',
                        area:['400px','200px'],
                        type: 1,
                        shade: 0.3,
                        title: '设置', //不显示标题
                        btn: ['终止'],
                        content: $('#form-progress'), //捕获的元素，注意：最好该指定的元素要存放在body最外层，否则可能被其它的相对元素所影响
                        yes: function(index, layero){
                            layer.close(progress_index);
                            apply_run =false;
                            toastr.warning("已经终止");
                        }
                    });

                    element.progress('progress', "0%");
                    apply_idx = 0;
                    apply_run =true;
                    apply_retry = 0;
                    apply_failed_idx_arr=[];
                    loopSetNodePulseWater();
                });

            }
            return false;
        });

        //停用
        form.on('submit(btn_set_stop)', function(data){
            var checkStatus = table.checkStatus('table'); //idTest 即为基础参数 id 对应的值

            var checkData = checkStatus.data;
            console.log(checkData); //获取选中行的数据
            if(checkData.length==0){
                toastr.warning("请勾选需要批量设置的饲喂器");
            }else{
                nodeParaArr=[];
                addrArr=[];
                enableArr=[];
                tnArr=[];
                set_mode_arr=[]
                for(var i=0;i<checkData.length;i++){
                    var nodePara = JSON.parse(checkData[i].para);
                    nodeParaArr.push(nodePara);
                    addrArr.push(checkData[i].addr);
                    enableArr.push(checkData[i].enable);
                    tnArr.push(checkData[i].tn);
                    set_mode_arr.push(EMODE_IDLE_NEW.toString());//停用模式
                }

                layer.confirm('确认对勾选的'+nodeParaArr.length.toString()+"个饲喂器 停用?", function(index){
                    layer.close(index); //再执行关闭
                    progress_index = layer.open({
                        //area: 'auto',
                        area:['400px','200px'],
                        type: 1,
                        shade: 0.3,
                        title: '设置', //不显示标题
                        btn: ['终止'],
                        content: $('#form-progress'), //捕获的元素，注意：最好该指定的元素要存放在body最外层，否则可能被其它的相对元素所影响
                        yes: function(index, layero){
                            layer.close(progress_index);
                            apply_run =false;
                            toastr.warning("已经终止");
                        }
                    });

                    element.progress('progress', "0%");
                    apply_idx = 0;
                    apply_run =true;
                    apply_retry = 0;
                    apply_failed_idx_arr=[];
                    loopSetNodeMode();
                });
            }
            return false;
        });

        //启用
        form.on('submit(btn_set_enable)', function(data){
            var checkStatus = table.checkStatus('table'); //idTest 即为基础参数 id 对应的值

            var checkData = checkStatus.data;
            console.log(checkData); //获取选中行的数据
            if(checkData.length==0){
                toastr.warning("请勾选需要批量设置的饲喂器");
            }else{
                nodeParaArr=[];
                addrArr=[];
                enableArr=[];
                tnArr=[];
                //feedPlanIdArr = [];
                
                var err_arr = [];
                set_mode_arr = [];
                for(var i=0;i<checkData.length;i++){
                    var nodePara = JSON.parse(checkData[i].para);
                    nodeParaArr.push(nodePara);
                    addrArr.push(checkData[i].addr);
                    enableArr.push(checkData[i].enable);
                    tnArr.push(checkData[i].tn);
                    if(checkData[i].feed_plan_id){
                        //feedPlanIdArr.push(checkData[i].feed_plan_id);
                        //查找方案对应的模式
                        for(var x=0;x<allPlanData.length;x++){
                            if(allPlanData[x].id == checkData[i].feed_plan_id){
                                var para =JSON.parse(allPlanData[x].para);
                                console.info("plan para",para);
                                var mode = para.Mode;
                                set_mode_arr.push(mode);
                                break;
                            }
                        }
                    }else{
                        //没有方案
                        err_arr.push(nodePara.Hnum+"未设置过方案,无法启用饲喂");
                    }
                }
                if(err_arr.length>0){
                    var str="无法启动:<br />";
                    for(var i=0;i<err_arr.length;i++){
                        str+=(err_arr[i])+"<br />";
                    }
                    layer.alert(str);
                    return false;
                }else{
                    //下发模式（启用）
                    if(set_mode_arr.length==0){
                        layer.alert("无法获取到当前设置的方案(无对应方案的权限),无法启用!");
                        return false;
                    }
                    console.info("set_mode_arr",set_mode_arr);
                    layer.confirm('确认对勾选的'+nodeParaArr.length.toString()+"个饲喂器 启用?", function(index){
                        layer.close(index); //再执行关闭
                        progress_index = layer.open({
                            //area: 'auto',
                            area:['400px','200px'],
                            type: 1,
                            shade: 0.3,
                            title: '设置', //不显示标题
                            btn: ['终止'],
                            content: $('#form-progress'), //捕获的元素，注意：最好该指定的元素要存放在body最外层，否则可能被其它的相对元素所影响
                            yes: function(index, layero){
                                layer.close(progress_index);
                                apply_run =false;
                                toastr.warning("已经终止");
                            }
                        });

                        element.progress('progress', "0%");
                        apply_idx = 0;
                        apply_run =true;
                        apply_retry = 0;
                        apply_failed_idx_arr=[];
                        loopSetNodeMode();
                    });
                }

            }
            return false;
        });

        //远程下料
        form.on('submit(on_btn_manul)', function(data){
            manul(data.field);
        });

        //设置耳标
        form.on('submit(btn_earmark)', function(data){
            saveEarmark(data.field);
        });

        form.on('submit(btn_pig_type)', function(data){
            savePigType(data.field);
        });

        form.on('submit(btn_pig_item_ok)', function(data){
            savePigItem(data.field);
        });

        form.on('submit(btn_pig_ok)', function(data){
            savePig(data.field);
        });

        form.on('submit(btn_auto_hnum)',function(data){
            console.info(data.field);

            autoSetHnum(data.field.prefix_idx,data.field.col);
        });
        
        
        //加载tree
        loadTree();

        resize();

        


    });

    function loopSetNodeParam() {
        if(!apply_run){
            return;
        }
        setNodeParam(addrArr[apply_idx],tnArr[apply_idx],enableArr[apply_idx],nodeParaArr[apply_idx]).then(function(res) {
            var hasErr=false;
            if(res.code>=0){
                //保存参数成功
                //更新进度条
                element.progress('progress', (((apply_idx+1)/nodeParaArr.length)*100).toFixed(1)+"%");
                console.info(nodeParaArr[apply_idx]);
                //toastr.info(nodeParaArr[apply_idx].Hnum+" "+nodeParaArr[apply_idx].Sn+" 下发成功");
                $("#progress-tips").html(nodeParaArr[apply_idx].Hnum+" "+nodeParaArr[apply_idx].Sn+" 下发成功");
            }
            else
            {
                //保存参数失败
                element.progress('progress', (((apply_idx+1)/nodeParaArr.length)*100).toFixed(1)+"%");
                //记录错误
                hasErr=true;
            }

            //进行下一个
            if(apply_idx == (nodeParaArr.length-1)){
                
                //全部结束
                $("#progress-tips").empty();
                layer.close(progress_index);
                apply_run =false;
                if(apply_failed_idx_arr.length==0){
                    layer.alert("已经全部成功完成");
                    $("#progress-tips").empty();
                    //读取一次全部参数todo
                    search();
                }else{
                    toastr.warning("已经完成，但部分参数未设置成功");
                    //弹出对话框
                    var str="以下饲喂器下发参数失败:<br />";
                    for(var i=0;i<apply_failed_idx_arr.length;i++){
                        var idx = apply_failed_idx_arr[i];
                        str+=(nodeParaArr[idx].Hnum+" "+nodeParaArr[idx].Sn)+"<br />";
                    }
                    layer.alert(str);
                }


                return;
                
            }else{
                if(hasErr){
                    if(apply_retry<retry_max){
                        apply_retry++;
                        //继续下发原来的
                        //toastr.info(nodeParaArr[apply_idx].Hnum+" "+nodeParaArr[apply_idx].Sn+" 重试第"+(apply_retry).toString()+"次...");
                        $("#progress-tips").html(nodeParaArr[apply_idx].Hnum+" "+nodeParaArr[apply_idx].Sn+" 重试第"+(apply_retry).toString()+"次...");
                    }else{
                        //超过重试次数，下一个
                        apply_failed_idx_arr.push(apply_idx);
                        apply_retry=0;
                        apply_idx++;
                    }
                }else{
                    apply_retry=0;
                    apply_idx++;
                }

                setTimeout(function(){
                    if(apply_run){
                        $("#progress-tips").html(nodeParaArr[apply_idx].Hnum+" "+nodeParaArr[apply_idx].Sn+" 下发参数中...");
                        loopSetNodeParam();
                    }
                },500);
            }
        });
    }

    function loopSetNodeDay() {
        if(!apply_run){
            return;
        }
        setNodeGday(addrArr[apply_idx],tnArr[apply_idx],set_day).then(function(res) {
            var hasErr=false;
            if(res.code>=0){
                //保存参数成功
                //更新进度条
                element.progress('progress', (((apply_idx+1)/nodeParaArr.length)*100).toFixed(1)+"%");
                console.info(nodeParaArr[apply_idx]);
                //toastr.info(nodeParaArr[apply_idx].Hnum+" "+nodeParaArr[apply_idx].Sn+" 下发成功");
                $("#progress-tips").html(nodeParaArr[apply_idx].Hnum+" "+nodeParaArr[apply_idx].Sn+" 下发成功");
            }
            else
            {
                //保存参数失败
                element.progress('progress', (((apply_idx+1)/nodeParaArr.length)*100).toFixed(1)+"%");
                //记录错误
                hasErr=true;
            }

            //进行下一个
            if(apply_idx == (nodeParaArr.length-1)){
                
                //全部结束
                //刷新参数
                readNMSWQGWPara(addrArr[apply_idx]).then(function(res) {
                    if(res.code>=0){
                        setTimeout(function(){search();},500);
                    }
                });
                
                $("#progress-tips").empty();
                layer.close(progress_index);
                apply_run =false;
                if(apply_failed_idx_arr.length==0){
                    layer.alert("已经全部成功完成");
                    $("#progress-tips").empty();
                }else{
                    toastr.warning("已经完成，但部分参数未设置成功");
                    //弹出对话框
                    var str="以下饲喂器下发参数失败:<br />";
                    for(var i=0;i<apply_failed_idx_arr.length;i++){
                        var idx = apply_failed_idx_arr[i];
                        str+=(nodeParaArr[idx].Hnum+" "+nodeParaArr[idx].Sn)+"<br />";
                    }
                    layer.alert(str);
                }
                return;
                
            }else{
                if(hasErr){
                    if(apply_retry<retry_max){
                        apply_retry++;
                        //继续下发原来的
                        //toastr.info(nodeParaArr[apply_idx].Hnum+" "+nodeParaArr[apply_idx].Sn+" 重试第"+(apply_retry).toString()+"次...");
                        $("#progress-tips").html(nodeParaArr[apply_idx].Hnum+" "+nodeParaArr[apply_idx].Sn+" 重试第"+(apply_retry).toString()+"次...");
                    }else{
                        //超过重试次数，下一个
                        apply_failed_idx_arr.push(apply_idx);
                        apply_retry=0;
                        apply_idx++;
                    }
                }else{
                    apply_retry=0;
                    apply_idx++;
                }

                setTimeout(function(){
                    if(apply_run){
                        $("#progress-tips").html(nodeParaArr[apply_idx].Hnum+" "+nodeParaArr[apply_idx].Sn+" 下发参数中...");
                        loopSetNodeDay();
                    }
                },500);
            }
        });
    }

    function loopSetNodeFeedWater() {
        if(!apply_run){
            return;
        }
        setNodeFeedWater(addrArr[apply_idx],tnArr[apply_idx],set_feed,set_water).then(function(res) {
            var hasErr=false;
            if(res.code>=0){
                //保存参数成功
                //更新进度条
                element.progress('progress', (((apply_idx+1)/nodeParaArr.length)*100).toFixed(1)+"%");
                console.info(nodeParaArr[apply_idx]);
                //toastr.info(nodeParaArr[apply_idx].Hnum+" "+nodeParaArr[apply_idx].Sn+" 下发成功");
                $("#progress-tips").html(nodeParaArr[apply_idx].Hnum+" "+nodeParaArr[apply_idx].Sn+" 下发成功");
            }
            else
            {
                //保存参数失败
                element.progress('progress', (((apply_idx+1)/nodeParaArr.length)*100).toFixed(1)+"%");
                //记录错误
                hasErr=true;
            }

            //进行下一个
            if(apply_idx == (nodeParaArr.length-1)){
                
                //全部结束
                
                
                $("#progress-tips").empty();
                layer.close(progress_index);
                apply_run =false;
                if(apply_failed_idx_arr.length==0){
                    layer.alert("已经全部成功完成");
                    $("#progress-tips").empty();
                }else{
                    toastr.warning("已经完成，但部分饲喂器未控制成功");
                    //弹出对话框
                    var str="以下饲喂器下发命令失败:<br />";
                    for(var i=0;i<apply_failed_idx_arr.length;i++){
                        var idx = apply_failed_idx_arr[i];
                        str+=(nodeParaArr[idx].Hnum+" "+nodeParaArr[idx].Sn)+"<br />";
                    }
                    layer.alert(str);
                }
                return;
                
            }else{
                if(hasErr){
                    if(apply_retry<retry_max){
                        apply_retry++;
                        //继续下发原来的
                        //toastr.info(nodeParaArr[apply_idx].Hnum+" "+nodeParaArr[apply_idx].Sn+" 重试第"+(apply_retry).toString()+"次...");
                        $("#progress-tips").html(nodeParaArr[apply_idx].Hnum+" "+nodeParaArr[apply_idx].Sn+" 重试第"+(apply_retry).toString()+"次...");
                    }else{
                        //超过重试次数，下一个
                        apply_failed_idx_arr.push(apply_idx);
                        apply_retry=0;
                        apply_idx++;
                    }
                }else{
                    apply_retry=0;
                    apply_idx++;
                }

                setTimeout(function(){
                    if(apply_run){
                        $("#progress-tips").html(nodeParaArr[apply_idx].Hnum+" "+nodeParaArr[apply_idx].Sn+" 下发命令中...");
                        loopSetNodeFeedWater();
                    }
                },500);
            }
        });
    }

    function loopSetNodePulseWater() {
        if(!apply_run){
            return;
        }
        setNodePulseWater(addrArr[apply_idx],tnArr[apply_idx],set_pulseWater).then(function(res) {
            var hasErr=false;
            if(res.code>=0){
                //保存参数成功
                //更新进度条
                element.progress('progress', (((apply_idx+1)/nodeParaArr.length)*100).toFixed(1)+"%");
                console.info(nodeParaArr[apply_idx]);
                //toastr.info(nodeParaArr[apply_idx].Hnum+" "+nodeParaArr[apply_idx].Sn+" 下发成功");
                $("#progress-tips").html(nodeParaArr[apply_idx].Hnum+" "+nodeParaArr[apply_idx].Sn+" 下发成功");
            }
            else
            {
                //保存参数失败
                element.progress('progress', (((apply_idx+1)/nodeParaArr.length)*100).toFixed(1)+"%");
                //记录错误
                hasErr=true;
            }

            //进行下一个
            if(apply_idx == (nodeParaArr.length-1)){
                
                //全部结束
                //刷新参数
                readNMSWQGWPara(addrArr[apply_idx]).then(function(res) {
                    if(res.code>=0){
                        setTimeout(function(){search();},500);
                    }
                });
                
                $("#progress-tips").empty();
                layer.close(progress_index);
                apply_run =false;
                if(apply_failed_idx_arr.length==0){
                    layer.alert("已经全部成功完成");
                    $("#progress-tips").empty();
                }else{
                    toastr.warning("已经完成，但部分参数未设置成功");
                    //弹出对话框
                    var str="以下饲喂器下发参数失败:<br />";
                    for(var i=0;i<apply_failed_idx_arr.length;i++){
                        var idx = apply_failed_idx_arr[i];
                        str+=(nodeParaArr[idx].Hnum+" "+nodeParaArr[idx].Sn)+"<br />";
                    }
                    layer.alert(str);
                }
                return;

                
            }else{
                if(hasErr){
                    if(apply_retry<retry_max){
                        apply_retry++;
                        //继续下发原来的
                        //toastr.info(nodeParaArr[apply_idx].Hnum+" "+nodeParaArr[apply_idx].Sn+" 重试第"+(apply_retry).toString()+"次...");
                        $("#progress-tips").html(nodeParaArr[apply_idx].Hnum+" "+nodeParaArr[apply_idx].Sn+" 重试第"+(apply_retry).toString()+"次...");
                    }else{
                        //超过重试次数，下一个
                        apply_failed_idx_arr.push(apply_idx);
                        apply_retry=0;
                        apply_idx++;
                    }
                }else{
                    apply_retry=0;
                    apply_idx++;
                }

                setTimeout(function(){
                    if(apply_run){
                        $("#progress-tips").html(nodeParaArr[apply_idx].Hnum+" "+nodeParaArr[apply_idx].Sn+" 下发参数中...");
                        loopSetNodePulseWater();
                    }
                },500);
            }
        });
    }

    function loopSetNodeCalFeed() {
        if(!apply_run){
            return;
        }
        setNodeCalFeed(addrArr[apply_idx],tnArr[apply_idx],set_calFeed).then(function(res) {
            var hasErr=false;
            if(res.code>=0){
                //保存参数成功
                //更新进度条
                element.progress('progress', (((apply_idx+1)/nodeParaArr.length)*100).toFixed(1)+"%");
                console.info(nodeParaArr[apply_idx]);
                //toastr.info(nodeParaArr[apply_idx].Hnum+" "+nodeParaArr[apply_idx].Sn+" 下发成功");
                $("#progress-tips").html(nodeParaArr[apply_idx].Hnum+" "+nodeParaArr[apply_idx].Sn+" 下发成功");
            }
            else
            {
                //保存参数失败
                element.progress('progress', (((apply_idx+1)/nodeParaArr.length)*100).toFixed(1)+"%");
                //记录错误
                hasErr=true;
            }

            //进行下一个
            if(apply_idx == (nodeParaArr.length-1)){
                
                //全部结束
                //刷新参数
                readNMSWQGWPara(addrArr[apply_idx]).then(function(res) {
                    if(res.code>=0){
                        setTimeout(function(){search();},500);
                    }
                });
                
                $("#progress-tips").empty();
                layer.close(progress_index);
                apply_run =false;
                if(apply_failed_idx_arr.length==0){
                    layer.alert("已经全部成功完成");
                    $("#progress-tips").empty();
                }else{
                    toastr.warning("已经完成，但部分参数未设置成功");
                    //弹出对话框
                    var str="以下饲喂器下发参数失败:<br />";
                    for(var i=0;i<apply_failed_idx_arr.length;i++){
                        var idx = apply_failed_idx_arr[i];
                        str+=(nodeParaArr[idx].Hnum+" "+nodeParaArr[idx].Sn)+"<br />";
                    }
                    layer.alert(str);
                }
                return;
                
                
            }else{
                if(hasErr){
                    if(apply_retry<retry_max){
                        apply_retry++;
                        //继续下发原来的
                        //toastr.info(nodeParaArr[apply_idx].Hnum+" "+nodeParaArr[apply_idx].Sn+" 重试第"+(apply_retry).toString()+"次...");
                        $("#progress-tips").html(nodeParaArr[apply_idx].Hnum+" "+nodeParaArr[apply_idx].Sn+" 重试第"+(apply_retry).toString()+"次...");
                    }else{
                        //超过重试次数，下一个
                        apply_failed_idx_arr.push(apply_idx);
                        apply_retry=0;
                        apply_idx++;
                    }
                }else{
                    apply_retry=0;
                    apply_idx++;
                }

                setTimeout(function(){
                    if(apply_run){
                        $("#progress-tips").html(nodeParaArr[apply_idx].Hnum+" "+nodeParaArr[apply_idx].Sn+" 下发参数中...");
                        loopSetNodeCalFeed();
                    }
                },500);
            }
        });
    }

    function loopSetNodeCalAD() {
        if(!apply_run){
            return;
        }
        SetNodeAD(addrArr[apply_idx],tnArr[apply_idx],set_calAD,set_calADR).then(function(res) {
            var hasErr=false;
            if(res.code>=0){
                //保存参数成功
                //更新进度条
                element.progress('progress', (((apply_idx+1)/nodeParaArr.length)*100).toFixed(1)+"%");
                console.info(nodeParaArr[apply_idx]);
                //toastr.info(nodeParaArr[apply_idx].Hnum+" "+nodeParaArr[apply_idx].Sn+" 下发成功");
                $("#progress-tips").html(nodeParaArr[apply_idx].Hnum+" "+nodeParaArr[apply_idx].Sn+" 下发成功");
            }
            else
            {
                //保存参数失败
                element.progress('progress', (((apply_idx+1)/nodeParaArr.length)*100).toFixed(1)+"%");
                //记录错误
                hasErr=true;
            }

            //进行下一个
            if(apply_idx == (nodeParaArr.length-1)){
                
                //全部结束
                //刷新参数
                readNMSWQGWPara(addrArr[apply_idx]).then(function(res) {
                    if(res.code>=0){
                        setTimeout(function(){search();},500);
                    }
                });
                
                $("#progress-tips").empty();
                layer.close(progress_index);
                apply_run =false;
                if(apply_failed_idx_arr.length==0){
                    layer.alert("已经全部成功完成");
                    $("#progress-tips").empty();
                }else{
                    toastr.warning("已经完成，但部分参数未设置成功");
                    //弹出对话框
                    var str="以下饲喂器下发参数失败:<br />";
                    for(var i=0;i<apply_failed_idx_arr.length;i++){
                        var idx = apply_failed_idx_arr[i];
                        str+=(nodeParaArr[idx].Hnum+" "+nodeParaArr[idx].Sn)+"<br />";
                    }
                    layer.alert(str);
                }
                return;
                
                
            }else{
                if(hasErr){
                    if(apply_retry<retry_max){
                        apply_retry++;
                        //继续下发原来的
                        //toastr.info(nodeParaArr[apply_idx].Hnum+" "+nodeParaArr[apply_idx].Sn+" 重试第"+(apply_retry).toString()+"次...");
                        $("#progress-tips").html(nodeParaArr[apply_idx].Hnum+" "+nodeParaArr[apply_idx].Sn+" 重试第"+(apply_retry).toString()+"次...");
                    }else{
                        //超过重试次数，下一个
                        apply_failed_idx_arr.push(apply_idx);
                        apply_retry=0;
                        apply_idx++;
                    }
                }else{
                    apply_retry=0;
                    apply_idx++;
                }

                setTimeout(function(){
                    if(apply_run){
                        $("#progress-tips").html(nodeParaArr[apply_idx].Hnum+" "+nodeParaArr[apply_idx].Sn+" 下发参数中...");
                        loopSetNodeCalAD();
                    }
                },500);
            }
        });
    }

    function loopSetNodeWaterPTTO() {
        if(!apply_run){
            return;
        }
        setNodeWaterPTTO(addrArr[apply_idx],tnArr[apply_idx],set_waterPTTO).then(function(res) {
            var hasErr=false;
            if(res.code>=0){
                //保存参数成功
                //更新进度条
                element.progress('progress', (((apply_idx+1)/nodeParaArr.length)*100).toFixed(1)+"%");
                console.info(nodeParaArr[apply_idx]);
                //toastr.info(nodeParaArr[apply_idx].Hnum+" "+nodeParaArr[apply_idx].Sn+" 下发成功");
                $("#progress-tips").html(nodeParaArr[apply_idx].Hnum+" "+nodeParaArr[apply_idx].Sn+" 下发成功");
            }
            else
            {
                //保存参数失败
                element.progress('progress', (((apply_idx+1)/nodeParaArr.length)*100).toFixed(1)+"%");
                //记录错误
                hasErr=true;
            }

            //进行下一个
            if(apply_idx == (nodeParaArr.length-1)){
                
                //全部结束
                //刷新参数
                readNMSWQGWPara(addrArr[apply_idx]).then(function(res) {
                    if(res.code>=0){
                        setTimeout(function(){search();},500);
                    }
                });
                
                $("#progress-tips").empty();
                layer.close(progress_index);
                apply_run =false;
                if(apply_failed_idx_arr.length==0){
                    layer.alert("已经全部成功完成");
                    $("#progress-tips").empty();
                }else{
                    toastr.warning("已经完成，但部分参数未设置成功");
                    //弹出对话框
                    var str="以下饲喂器下发参数失败:<br />";
                    for(var i=0;i<apply_failed_idx_arr.length;i++){
                        var idx = apply_failed_idx_arr[i];
                        str+=(nodeParaArr[idx].Hnum+" "+nodeParaArr[idx].Sn)+"<br />";
                    }
                    layer.alert(str);
                }
                return;
                
            }else{
                if(hasErr){
                    if(apply_retry<retry_max){
                        apply_retry++;
                        //继续下发原来的
                        //toastr.info(nodeParaArr[apply_idx].Hnum+" "+nodeParaArr[apply_idx].Sn+" 重试第"+(apply_retry).toString()+"次...");
                        $("#progress-tips").html(nodeParaArr[apply_idx].Hnum+" "+nodeParaArr[apply_idx].Sn+" 重试第"+(apply_retry).toString()+"次...");
                    }else{
                        //超过重试次数，下一个
                        apply_failed_idx_arr.push(apply_idx);
                        apply_retry=0;
                        apply_idx++;
                    }
                }else{
                    apply_retry=0;
                    apply_idx++;
                }

                setTimeout(function(){
                    if(apply_run){
                        $("#progress-tips").html(nodeParaArr[apply_idx].Hnum+" "+nodeParaArr[apply_idx].Sn+" 下发参数中...");
                        loopSetNodeWaterPTTO();
                    }
                },500);
            }
        });
    }
    
    function loopSetNodeMode() {
        if(!apply_run){
            return;
        }
        SetNodeMode(addrArr[apply_idx],tnArr[apply_idx],set_mode_arr[apply_idx]).then(function(res) {
            var hasErr=false;
            if(res.code>=0){
                //保存参数成功
                //更新进度条
                element.progress('progress', (((apply_idx+1)/nodeParaArr.length)*100).toFixed(1)+"%");
                console.info(nodeParaArr[apply_idx]);
                //toastr.info(nodeParaArr[apply_idx].Hnum+" "+nodeParaArr[apply_idx].Sn+" 下发成功");
                $("#progress-tips").html(nodeParaArr[apply_idx].Hnum+" "+nodeParaArr[apply_idx].Sn+" 下发成功");
            }
            else
            {
                //保存参数失败
                element.progress('progress', (((apply_idx+1)/nodeParaArr.length)*100).toFixed(1)+"%");
                //记录错误
                hasErr=true;
            }

            //进行下一个
            if(apply_idx == (nodeParaArr.length-1)){
                
                //全部结束
                //刷新参数
                readNMSWQGWPara(addrArr[apply_idx]).then(function(res) {
                    if(res.code>=0){
                        setTimeout(function(){search();},500);
                    }
                });
                
                $("#progress-tips").empty();
                layer.close(progress_index);
                apply_run =false;
                if(apply_failed_idx_arr.length==0){
                    layer.alert("已经全部成功完成");
                    $("#progress-tips").empty();
                }else{
                    toastr.warning("已经完成，但部分参数未设置成功");
                    //弹出对话框
                    var str="以下饲喂器下发参数失败:<br />";
                    for(var i=0;i<apply_failed_idx_arr.length;i++){
                        var idx = apply_failed_idx_arr[i];
                        str+=(nodeParaArr[idx].Hnum+" "+nodeParaArr[idx].Sn)+"<br />";
                    }
                    layer.alert(str);
                }
                return;
                
            }else{
                if(hasErr){
                    if(apply_retry<retry_max){
                        apply_retry++;
                        //继续下发原来的
                        //toastr.info(nodeParaArr[apply_idx].Hnum+" "+nodeParaArr[apply_idx].Sn+" 重试第"+(apply_retry).toString()+"次...");
                        $("#progress-tips").html(nodeParaArr[apply_idx].Hnum+" "+nodeParaArr[apply_idx].Sn+" 重试第"+(apply_retry).toString()+"次...");
                    }else{
                        //超过重试次数，下一个
                        apply_failed_idx_arr.push(apply_idx);
                        apply_retry=0;
                        apply_idx++;
                    }
                }else{
                    apply_retry=0;
                    apply_idx++;
                }

                setTimeout(function(){
                    if(apply_run){
                        $("#progress-tips").html(nodeParaArr[apply_idx].Hnum+" "+nodeParaArr[apply_idx].Sn+" 下发参数中...");
                        loopSetNodeMode();
                    }
                },500);
            }
        });
    }

    function loopSetNodeHnum() {
        if(!apply_run){
            return;
        }
        SetNodeHnum(addrArr[apply_idx],tnArr[apply_idx],hnumArr[apply_idx]).then(function(res) {
            var hasErr=false;
            if(res.code>=0){
                //保存参数成功
                //更新进度条
                element.progress('progress', (((apply_idx+1)/nodeParaArr.length)*100).toFixed(1)+"%");
                console.info(nodeParaArr[apply_idx]);
                //toastr.info(nodeParaArr[apply_idx].Hnum+" "+nodeParaArr[apply_idx].Sn+" 下发成功");
                $("#progress-tips").html(hnumArr[apply_idx]+" "+nodeParaArr[apply_idx].Sn+" 下发成功");
            }
            else
            {
                //保存参数失败
                element.progress('progress', (((apply_idx+1)/nodeParaArr.length)*100).toFixed(1)+"%");
                //记录错误
                hasErr=true;
            }

            //进行下一个
            if(apply_idx == (nodeParaArr.length-1)){
                
                //全部结束
                //刷新参数
                readNMSWQGWPara(addrArr[apply_idx]).then(function(res) {
                    if(res.code>=0){
                        setTimeout(function(){search();},500);
                    }
                });
                
                $("#progress-tips").empty();
                layer.close(progress_index);
                apply_run =false;
                if(apply_failed_idx_arr.length==0){
                    layer.alert("已经全部成功完成");
                    $("#progress-tips").empty();
                }else{
                    toastr.warning("已经完成，但部分参数未设置成功");
                    //弹出对话框
                    var str="以下饲喂器下发参数失败:<br />";
                    for(var i=0;i<apply_failed_idx_arr.length;i++){
                        var idx = apply_failed_idx_arr[i];
                        str+=(hnumArr[idx]+" "+nodeParaArr[idx].Sn)+"<br />";
                    }
                    layer.alert(str);
                }
                return;
                
            }else{
                if(hasErr){
                    if(apply_retry<retry_max){
                        apply_retry++;
                        //继续下发原来的
                        //toastr.info(nodeParaArr[apply_idx].Hnum+" "+nodeParaArr[apply_idx].Sn+" 重试第"+(apply_retry).toString()+"次...");
                        $("#progress-tips").html(hnumArr[apply_idx]+" "+nodeParaArr[apply_idx].Sn+" 重试第"+(apply_retry).toString()+"次...");
                    }else{
                        //超过重试次数，下一个
                        apply_failed_idx_arr.push(apply_idx);
                        apply_retry=0;
                        apply_idx++;
                    }
                }else{
                    apply_retry=0;
                    apply_idx++;
                }

                setTimeout(function(){
                    if(apply_run){
                        $("#progress-tips").html(hnumArr[apply_idx]+" "+nodeParaArr[apply_idx].Sn+" 下发参数中...");
                        loopSetNodeHnum();
                    }
                },500);
            }
        });
    }

    //设置参数/应用方案
    function setNodeParam(addr,tn,enable,nodePara){

        //兼容26版本
        if(!nodePara.WaterDelay){
            nodePara.WaterDelay = nodePara.ReverseTimes;
        }
        if(!nodePara.PtTimeDelay){
            nodePara.PtTimeDelay = nodePara.ReverseTurns;
        }
        if(!nodePara.CurIdle){
            nodePara.CurIdle = nodePara.TbPTime[0];
        }
        //20240715 先默认打开且隐藏首次触碰当诱食处理
        nodePara.Tmr_flag_bits[2] = true;

        
        var promise = new Promise(function(resolve, reject) {
            console.info("node_model:"+node_model);
            var url = "";
            if(node_model=="feed"){
                url = '../Api/Device/Gw/NodeParam';
            }else if(node_model=="fg"){
                url = '../Api/Device/Gw/NodeFgParam';
            }

            $.ajax({
                type: 'PUT',
                url: url,
                data: {feed_plan_id:feed_plan_id,addr:addr,tn:tn,enable:enable,params:JSON.stringify(nodePara)},
                beforeSend: function(request) {
                    request.setRequestHeader("Authorization", 'Bearer '+window.localStorage.getItem("token"));
                },
                success: function (data) {

                    if (data && data.code>=0) {
                        resolve(data);
                    }else{
                        resolve(data);
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    reject(err);
                },
                complete: function(XMLHttpRequest, textStatus) {

                },
                dataType: "json"
            });
        });
        return promise;
    }


    //设置日龄
    function setNodeGday(addr,tn,day){
        var promise = new Promise(function(resolve, reject) {
            $.ajax({
                type: 'PUT',
                url: '../Api/Device/Gw/SetNodeDay',
                data: {addr:addr,tn:tn,day:day},
                beforeSend: function(request) {
                    request.setRequestHeader("Authorization", 'Bearer '+window.localStorage.getItem("token"));
                },
                success: function (data) {

                    if (data && data.code>=0) {
                        resolve(data);
                    }else{
                        resolve(data);
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    reject(err);
                },
                complete: function(XMLHttpRequest, textStatus) {

                },
                dataType: "json"
            });
        });
        return promise;
    }

    //远程下料/水
    function setNodeFeedWater(addr,tn,feed,water){
        var promise = new Promise(function(resolve, reject) {
            $.ajax({
                type: 'PUT',
                url: '../Api/Device/Gw/ManualFeed',
                data: {addr:addr,tn:tn,feed:feed,water:water},
                beforeSend: function(request) {
                    request.setRequestHeader("Authorization", 'Bearer '+window.localStorage.getItem("token"));
                },
                success: function (data) {

                    if (data && data.code>=0) {
                        resolve(data);
                    }else{
                        resolve(data);
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    reject(err);
                },
                complete: function(XMLHttpRequest, textStatus) {

                },
                dataType: "json"
            });
        });
        return promise;
    }
    //设置水阀校准
    function setNodePulseWater(addr,tn,pulseWater){
        var promise = new Promise(function(resolve, reject) {
            $.ajax({
                type: 'PUT',
                url: '../Api/Device/Gw/SetNodeCalcWater',
                data: {addr:addr,tn:tn,pulseWater:pulseWater},
                beforeSend: function(request) {
                    request.setRequestHeader("Authorization", 'Bearer '+window.localStorage.getItem("token"));
                },
                success: function (data) {

                    if (data && data.code>=0) {
                        resolve(data);
                    }else{
                        resolve(data);
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    reject(err);
                },
                complete: function(XMLHttpRequest, textStatus) {

                },
                dataType: "json"
            });
        });
        return promise;
    }

    //设置10圈出料
    function setNodeCalFeed(addr,tn,calFeed){
        var promise = new Promise(function(resolve, reject) {
            $.ajax({
                type: 'PUT',
                url: '../Api/Device/Gw/SetNodeCalcFeed',
                data: {addr:addr,tn:tn,calFeed:calFeed},
                beforeSend: function(request) {
                    request.setRequestHeader("Authorization", 'Bearer '+window.localStorage.getItem("token"));
                },
                success: function (data) {

                    if (data && data.code>=0) {
                        resolve(data);
                    }else{
                        resolve(data);
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    reject(err);
                },
                complete: function(XMLHttpRequest, textStatus) {

                },
                dataType: "json"
            });
        });
        return promise;
    }

    //设置水压
    function setNodeWaterPTTO(addr,tn,waterPTTO){
        var promise = new Promise(function(resolve, reject) {
            $.ajax({
                type: 'PUT',
                url: '../Api/Device/Gw/SetNodeWaterPTTO',
                data: {addr:addr,tn:tn,waterPTTO:waterPTTO},
                beforeSend: function(request) {
                    request.setRequestHeader("Authorization", 'Bearer '+window.localStorage.getItem("token"));
                },
                success: function (data) {

                    if (data && data.code>=0) {
                        resolve(data);
                    }else{
                        resolve(data);
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    reject(err);
                },
                complete: function(XMLHttpRequest, textStatus) {

                },
                dataType: "json"
            });
        });
        return promise;
    }
    
    //读取参数
    function readNMSWQGWPara(addr){
        var promise = new Promise(function(resolve, reject) {
            $.ajax({
                type: 'GET',
                url: '../Api/Device/Gw/Param',
                data: {addr:addr},
                beforeSend: function(request) {
                    request.setRequestHeader("Authorization", 'Bearer '+window.localStorage.getItem("token"));
                },
                success: function (data) {

                    if (data && data.code>=0) {
                        resolve(data);
                    }else{
                        resolve(data);
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    reject(err);
                },
                complete: function(XMLHttpRequest, textStatus) {

                },
                dataType: "json"
            });
        });
        return promise;
    }

    //切换模式
    function SetNodeMode(addr,tn,mode){
        var promise = new Promise(function(resolve, reject) {
            $.ajax({
                type: 'PUT',
                url: '../Api/Device/Gw/SetNodeMode',
                data: {addr:addr,tn:tn,mode:mode},
                beforeSend: function(request) {
                    request.setRequestHeader("Authorization", 'Bearer '+window.localStorage.getItem("token"));
                },
                success: function (data) {

                    if (data && data.code>=0) {
                        resolve(data);
                    }else{
                        resolve(data);
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    reject(err);
                },
                complete: function(XMLHttpRequest, textStatus) {

                },
                dataType: "json"
            });
        });
        return promise;
    }

    //设置栏位
    function SetNodeHnum(addr,tn,hnum){
        var promise = new Promise(function(resolve, reject) {
            $.ajax({
                type: 'PUT',
                url: '../Api/Device/Gw/SetNodeHnum',
                data: {addr:addr,tn:tn,hnum:hnum},
                beforeSend: function(request) {
                    request.setRequestHeader("Authorization", 'Bearer '+window.localStorage.getItem("token"));
                },
                success: function (data) {

                    if (data && data.code>=0) {
                        resolve(data);
                    }else{
                        resolve(data);
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    reject(err);
                },
                complete: function(XMLHttpRequest, textStatus) {

                },
                dataType: "json"
            });
        });
        return promise;
    }

    //设置AD
    function SetNodeAD(addr,tn,calAD,calADR){
        var promise = new Promise(function(resolve, reject) {
            $.ajax({
                type: 'PUT',
                url: '../Api/Device/Gw/SetNodeAD',
                data: {addr:addr,tn:tn,calAD:calAD,calADR:calADR},
                beforeSend: function(request) {
                    request.setRequestHeader("Authorization", 'Bearer '+window.localStorage.getItem("token"));
                },
                success: function (data) {

                    if (data && data.code>=0) {
                        resolve(data);
                    }else{
                        resolve(data);
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    reject(err);
                },
                complete: function(XMLHttpRequest, textStatus) {

                },
                dataType: "json"
            });
        });
        return promise;
    }

    //栏舍基本信息
    function getHouse(houseid){
        var promise = new Promise(function(resolve, reject) {
            $.ajax({
                type: 'GET',
                url: '../Api/House',
                data: {id:houseid},
                beforeSend: function(request) {
                    request.setRequestHeader("Authorization", 'Bearer '+window.localStorage.getItem("token"));
                },
                success: function (data) {

                    if (data && data.code>=0) {
                        resolve(data);
                    }else{
                        resolve(data);
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    reject(err);
                },
                complete: function(XMLHttpRequest, textStatus) {

                },
                dataType: "json"
            });
        });
        return promise;
    }

    //栏舍汇总信息
    function getHouseSummaryInfo(houseid){
        var promise = new Promise(function(resolve, reject) {
            $.ajax({
                type: 'GET',
                url: '../Api/House/SummaryInfo',
                data: {id:houseid},
                beforeSend: function(request) {
                    request.setRequestHeader("Authorization", 'Bearer '+window.localStorage.getItem("token"));
                },
                success: function (data) {

                    if (data && data.code>=0) {
                        resolve(data);
                    }else{
                        resolve(data);
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    reject(err);
                },
                complete: function(XMLHttpRequest, textStatus) {

                },
                dataType: "json"
            });
        });
        return promise;
    }


    //自动填写栏位号
    function autoSetHnum(){
        auto_hnum = true;
        loadNodesTable();
    }

    function getFont(treeId, node) {
        return node.font ? node.font : {};
    }


    function deepCopy(obj) {
        if (typeof obj != 'object') {
            return obj;
        }
        var newobj = {};
        for (var attr in obj) {
            newobj[attr] = deepCopy(obj[attr]);
        }
        return newobj;
    }

    

    //初始化表格
    function loadNodesTable(){
        calFeedErr = false;
        var obj=form.val("form_search");
        console.info(obj);
        if(selectedTreeNode.type=="house"){
            obj.houseid = selectedTreeNode.id;
        }else if(selectedTreeNode.type=="farm"){
            obj.farmid = selectedTreeNode.id;
        }else if(selectedTreeNode.type=="hnum"){
            obj.hnum_prefix = selectedTreeNode.hnum_prefix;
            obj.houseid = selectedTreeNode.houseid;
        }
        obj.device_type="DMXFGW";
        console.info("houstype=",selectedTreeNode.house_type)

        var edit = '';
        for(var i=0;i<actions.length;i++){
            if(actions[i].action_id == 'edit'){
                edit = "text";
                break;
            }
        }
        console.info("edit=",edit);
        tableOptions = {
            elem: '#table'

            //,url: "../Api/Device/Feednode"
            ,height: 'full-80'
            ,data:[]
            ,page:false
            /*,initSort: {
                field: 'tn' //排序字段，对应 cols 设定的各字段名
                ,type: 'asc' //排序方式  asc: 升序、desc: 降序、null: 默认排序
            }*/
            ,limit:9999
            ,toolbar: '#table_toolbar' //开启头部工具栏，并为其绑定左侧模板
            ,defaultToolbar: ['filter', 'exports']
            ,title: ''
            ,even:true
            ,size: 'sm' //小尺寸的表格
            //,skin: 'nob' //无框风格
            ,cols: [[
                {type: 'checkbox',title:'全选',fixed: 'left'}
                /*,{field:'housename', title:'栏舍', sort: false,minWidth:100, templet: function(d) {
                        if(d.housename && d.housename.length>0){
                            return d.housename;
                        }else{
                            return "<span class='layui-text-red'>尚未设置</span>";
                        }
                    }}*/
                ,{field:'hnum', title:'栏位<span id="hnum_menu" class="layui-badge" ><i id="hnum_menu_hint" class="layui-text-xs layui-text-orange layui-icon layui-icon-more-vertical"></i></span>',align:'center',width:80,fixed: 'left',edit:edit, sort: false}
                ,{field:'online', title:'状态',width:100,align:'center', sort: false,templet: function(d){
                        var html = "";
                        
                        if(d.online){
                            html+="<span class=\"layui-badge-dot layui-bg-blue\"></span> 在线"
                        }else{
                            html+="<span class=\"layui-badge-dot layui-bg-black\"></span>  离线"
                        }

                        if(d.alarm || d.alarm_ext){
                            console.info("alarm")
                            html+=" <span class='layui-anim ' id='alarm-tip-"+d.sn+"'><i class='layui-text-xs layui-icon layui-text-red layui-icon-notice'></i></span>";
                        }

                        /*var para = JSON.parse(d.para);
                        var status = JSON.parse(d.status);
                        
                        if(para && status){
                            if(parseInt(para.CalADR)<parseInt(status.Adval)){
                                // d.other="无水";
                                // html += "<button class='layui-btn layui-btn-xs' style='margin-left: 0.2rem;background-color: #FFB800;'>";
                                // html+= (d.other);
                                // html+=" </button>";
                                html+="<i id='nowater-tip-"+d.sn+"' class='iconfont icon-wuyansewushuidi layui-text-xs layui-text-black'></i>"
                            }else if(parseInt(para.CalAD)>parseInt(status.Adval)){
                                // d.other="有水";
                                // html += "<button class='layui-btn layui-btn-xs' style='margin-left: 0.2rem;background-color: #1E9FFF;'>";
                                // html+= (d.other);
                                // html+=" </button>";
                                html+="<i id='water-tip-"+d.sn+"' class='iconfont icon-shui layui-text-xs layui-text-blue'></i>"
                            }
                        }*/
                        return html;
                    }}
                ,{field:'model', title:'设备',width:90,align:'center', sort: false, templet: function(d) {
                    var html = "";
                    if(!d.model || d.model=="feed"){
                        html = "<span class='layui-badge-rim'>"+"饲喂器 "+"</span>";
                    }else if(d.model && d.model=="fg"){
                        html = "<span class='layui-badge-rim'>"+"粥料器 "+"</span>";
                    }
                    return html;
                }}
                ,{field:'sn', title:'SN码',hide:(is_admin?false:true),width:90, sort: false,templet: function(d) {   
                    //补全SN到8位，前面补0
                    //var sn = parseInt(d.sn);
                    //sn = sn.toString().padStart(8, '0');
                    //return sn;
                    return d.sn;
                }}
                ,{field:'mode', title:'模式状态',width:110,align:'center', sort: false, templet: function(d) {
                        var para_str = d.para;
                        if(para_str){
                            var para = JSON.parse(para_str);
                            var mode = para.Mode;
                            var day = para.Gday;
                            var modestr = "";
                            if(!d.model || d.model=="feed"){
                                modestr = decodeModeNew(mode);
                            }else if(d.model && d.model=="fg"){
                                modestr = decodeFgMode(mode);
                            }
                            
                            if(mode==0){
                                return "<span class='layui-text-orange'>"+modestr+"</span> "+"<span class='layui-text-orange'>"+day+"天</span>";
                            }else{
                                return "<span class=''>"+modestr+"</span> "+"<span class=''>"+day+"天</span>";
                            }
                        }
                        
                    }}
                ,{field:'feed_plan_name_new', title:'当前饲喂方案',align:'center',minWidth:120, sort: false, templet: function(d) {
                        var html="";
                        if(d.feed_plan_id && d.feed_plan_name_new){
                            html+= "<span id=plan-"+d.sn+" lay-event='feed_plan' class='layui-text-xs hand layui-text-blue '>"+  d.feed_plan_name_new+"</span>";
                            // return "<span lay-event='feed_plan' class='layui-badge-rim'> "+  d.feed_plan_name_new+"</span>"
                        }else{
                            html+= "<span id=plan-"+d.sn+" lay-event='feed_plan' class='layui-text-xs hand layui-text-orange '> - </span>";
                        }
                        /*var para = JSON.parse(d.para);
                        var status = JSON.parse(d.status);
                        if(para && status){
                            if(para.CalFeed){
                                if(para.CalFeed=="2200"||para.CalFeed=="3200"||para.CalFeed=="1000"){
                                    calFeedErr = true;
                                    html+="<span class='mr-left-md '><i id='calFeed-tip-"+d.sn+"' class='layui-icon layui-icon-tips layui-text-xs layui-text-black'></i></span>";
                                }
                            }
                        }*/
                        return html;
                    }}
                ,{field:'pro', title:'头均采食/标准采食(kg)',minWidth:140, sort: false, templet: function(d) {
                    if(1){
                        var html = "";
                        var mode_str = "";
                        if(!d.model || d.model=="feed"){
                            if(d.mode==0 || d.mode==5){
                                mode_str = "stop";
                            }
                            else if(d.mode==3||d.mode==4){
                                mode_str = "fat";
                            }
                            else if(d.mode==1||d.mode==2){
                                mode_str = "la";
                            }

                        }else if(d.model && d.model=="fg"){
                            if(d.mode==0 || d.mode==3){
                                mode_str = "stop";
                            }
                            else if(d.mode==1||d.mode==2){
                                mode_str = "fat";
                            }
                        }
                        if(mode_str == "stop"){
                            var html = "";
                            
                            html = "<span lay-event=\"feed_his\" class='layui-text-xs layui-text-black hand'>-</span>";
                            return html;
                        }
                        else if(mode_str == "fat"){
                            var pig_num = d.pig_num>0?d.pig_num:1;
                            var total_feed = parseFloat(d.day_use_feed_auto)+parseFloat(d.day_use_feed_man);
                            var feed = parseFloat((total_feed/pig_num).toFixed(2).toString())
                            var per = parseFloat(feed/parseFloat(d.standard)*100);
                            console.info("per",per);
                            var feed_str = feed+"/"+ d.standard.toFixed(2).toString();
                            var per = parseFloat(per.toFixed(1).toString()).toString();
                            var per_str = "("+per+"%)";

                            var color="";
                            var bgColor="";
                            if(per>=99){
                                color="layui-text-green-light";
                                bgColor="layui-bg-green";
                            }else if(per>=80 && per<99){
                                color="layui-text-orange";
                                bgColor="layui-bg-orange";
                            }else{
                                color="layui-text-orange";
                                bgColor="layui-bg-orange";
                            }

                            var html = "";
                            if(1==1){
                                html = "<span lay-event=\"feed_his\" class='layui-text-xs hand "+color+"'>"+  feed_str+per_str+"</span>";
                            }else{
                                html = "<span lay-event=\"feed_his\" class='layui-text-xs hand "+color+"'>"+  feed_str+per_str+"</span>";
                            }

                            
                            html+="<div class='layui-progress' lay-event=\"feed_his\"><div class='layui-progress-bar "+bgColor+"'  lay-percent='"+per+"%'></div></div>";
                            return html;
                        }
                        else if(mode_str == "la"){
                            var pig_num = d.pig_num>0?d.pig_num:1;
                            var total_feed = parseFloat(d.day_use_feed_auto)+parseFloat(d.day_use_feed_man);
                            var feed = parseFloat((total_feed/pig_num).toFixed(2).toString())
                            var per = parseFloat(feed/parseFloat(d.low_standard)*100);
                            console.info("per",per);
                            var feed_str = feed+"/"+ d.low_standard.toFixed(2).toString();
                            var per = parseFloat(per.toFixed(1).toString()).toString();
                            var per_str = "("+per+"%)";

                            var color="";
                            var bgColor="";
                            if(per>=99){
                                color="layui-text-green-light";
                                bgColor="layui-bg-green";
                            }else if(per>=80 && per<99){
                                color="layui-text-orange";
                                bgColor="layui-bg-orange";
                            }else{
                                color="layui-text-orange";
                                bgColor="layui-bg-orange";
                            }

                            var html = "";
                            if(1==1){
                                //html = "<span lay-event=\"feed_his\" class='layui-text-xs hand "+color+"'>"+  feed_str+per_str+" (手:"+parseFloat(parseFloat(d.day_use_feed_man).toFixed(2)).toString()+")</span>";
                                html = "<span lay-event=\"feed_his\" class='layui-text-xs hand "+color+"'>"+  feed_str+per_str+"</span>";
                            }else{
                                html = "<span lay-event=\"feed_his\" class='layui-text-xs hand "+color+"'>"+  feed_str+per_str+"</span>";
                            }

                            
                            html+="<div class='layui-progress' lay-event=\"feed_his\"><div class='layui-progress-bar "+bgColor+"'  lay-percent='"+per+"%'></div></div>";
                            return html;
                        }
                    }
                    
                }}
                ,{field:'feed', title:'总下料(kg)',width:140, sort: false, templet: function(d) {
                    var mode_str = "";
                    if(!d.model || d.model=="feed"){
                        if(d.mode==0 || d.mode==5){
                            mode_str = "stop";
                        }
                        else if(d.mode==3||d.mode==4){
                            mode_str = "fat";
                        }
                        else if(d.mode==1||d.mode==2){
                            mode_str = "la";
                        }

                    }else if(d.model && d.model=="fg"){
                        if(d.mode==0 || d.mode==3){
                            mode_str = "stop";
                        }
                        else if(d.mode==1||d.mode==2){
                            mode_str = "fat";
                        }
                    }

                    if(mode_str == "stop" || mode_str == "fat"){
                        //保育育肥自由采食，不显示目标和进度
                        if(!d.day_use_feed_auto && !d.day_use_feed_man){
                            return "0";
                        }
                        var feed = parseFloat(d.day_use_feed_auto)+parseFloat(d.day_use_feed_man);
                        var feed_str = parseFloat(feed.toFixed(2).toString()).toString();
                        
                        var html = "";
                        if(1==1){
                            //html = "<span lay-event=\"feed_his\" class='layui-text-xs layui-text-black hand'>"+  feed_str+" (手:"+parseFloat(parseFloat(d.day_use_feed_man).toFixed(2)).toString()+")</span>";
                            html = "<span lay-event=\"feed_his\" class='layui-text-xs layui-text-black hand'>"+  feed_str+"</span>";
                        }else{
                            html = "<span lay-event=\"feed_his\" class='layui-text-xs layui-text-black hand'>"+  feed_str+"</span>";
                        }
                        
                        return html;
                    }
                    else
                    {
                        if(!d.day_use_feed_auto && !d.day_use_feed_man){
                            return "0";
                        }
                        var feed = parseFloat(d.day_use_feed_auto)+parseFloat(d.day_use_feed_man);
                        //var water = parseFloat(d.day_use_water_auto)+parseFloat(d.day_use_water_man);
                        var per = parseFloat(feed/parseFloat(d.max_feed)*100);
                        console.info("per",per);

                        var feed_str = parseFloat(feed.toFixed(2).toString()).toString()+"/"+ d.max_feed;
                        var per = parseFloat(per.toFixed(1).toString()).toString();
                        var per_str = "("+per+"%)";

                        var color="";
                        var bgColor="";
                        if(d.max_feed && parseFloat(d.max_feed)==0){
                            color="layui-text-black";
                            bgColor="layui-bg-black";
                            per_str="";
                        }else{
                            if(per>=99){
                            color="layui-text-green-light";
                            bgColor="layui-bg-green";
                            }else if(per>=80 && per<99){
                                color="layui-text-orange";
                                bgColor="layui-bg-orange";
                            }else{
                                color="layui-text-orange";
                                bgColor="layui-bg-orange";
                            }
                        }

                        var html = "";
                        if(1==1){
                            //html = "<span lay-event=\"feed_his\" class='layui-text-xs hand "+color+"'>"+  feed_str+per_str+" (手:"+parseFloat(parseFloat(d.day_use_feed_man).toFixed(2)).toString()+")</span>";
                            html = "<span lay-event=\"feed_his\" class='layui-text-xs hand "+color+"'>"+  feed_str+per_str+"</span>";
                        }else{
                            html = "<span lay-event=\"feed_his\" class='layui-text-xs hand "+color+"'>"+  feed_str+per_str+"</span>";
                        }

                        
                        html+="<div class='layui-progress' lay-event=\"feed_his\"><div class='layui-progress-bar "+bgColor+"'  lay-percent='"+per+"%'></div></div>";
                        return html;
                    }
                    
                }}
                ,{field:'day_use_feed_man', title:'自动(kg)',width:80, sort: false, templet: function(d) {
                        if(d.day_use_feed_auto && d.day_use_feed_auto>0){
                            return parseFloat(parseFloat(d.day_use_feed_auto).toFixed(2)).toString();
                        }else{
                            return "0";
                        }
                    }}
                ,{field:'day_use_feed_man', title:'手动(kg)',width:80, sort: false, templet: function(d) {
                        if(d.day_use_feed_man && d.day_use_feed_man>0){
                            return parseFloat(parseFloat(d.day_use_feed_man).toFixed(2)).toString();
                        }else{
                            return "";
                        }
                    }}
                
                ,{field:'water', title:'下水量(L)',width:90, sort: false, templet: function(d) {
                        //var feed = parseFloat(d.day_use_feed_auto)+parseFloat(d.day_use_feed_man);
                        var water = parseFloat(d.day_use_water_auto)+parseFloat(d.day_use_water_man);
                        return  parseFloat(water.toFixed(2).toString()).toString();
                    }}
                ,{field:'pig_num', title:'猪只',width:80, sort: false,align:'center',edit:edit, templet: function(d) {
                        if(d.pig_num){
                            return "<span class='hand layui-text-xs ' >"+d.pig_num+"</span>";
                        }else{
                            return "<span class='hand layui-text-xs ' >-</span>";
                        }
                    }}
                ,{field:'son',hide:(selectedTreeNode.house_type<=2?false:true), title:'仔猪',edit:edit,width:80, sort: false,align:'center', templet: function(d) {
                        if(d.mode==EMODE_LACTATION_NEW && d.son){
                            return d.son;
                        }else{
                            return "-";
                        }
                    }}
                ,{field:'ad', title:'探针值',hide:(is_admin?false:true),width:80 ,sort: false,templet:function(d){
                    var html = "";
                    var para = JSON.parse(d.para);
                    var status = JSON.parse(d.status);
                    
                    if(para && status){
                        if(parseInt(para.CalADR)<parseInt(status.Adval)){
                            //无水黄色显示
                            html+="<span class='layui-text-gray'>"+status.Adval+"</span>"
                            // html += "<button class='layui-btn layui-btn-xs' style='margin-left: 0.2rem;background-color: #FFB800;'>";
                            // html+= (d.other);
                            // html+=" </button>";
                        }else if(parseInt(para.CalAD)>parseInt(status.Adval)){
                            //有水蓝色显示
                            html+="<span class='layui-text-blue'>"+status.Adval+"</span>"
                        }else{
                            html+="<span class='layui-text-orange'>"+status.Adval+"</span>"
                        }
                    }

                    return html;
                }}
                ,{field:'', title:'', width:90,sort: false,align:'center',fixed: 'right', templet: function(d) {
                    var html = "";
                    html = '<button class="layui-btn layui-btn-xs layui-btn-normal layui-btn-primary action-btn" data-sn="'+d.sn+'">操作<i class="layui-icon layui-icon-triangle-d"></i></button> ';
                    return html;
                }}
            ]]
            ,done: function(res, curr, count){
                allData = res.data;
                element.render();
                var menuData = [{
                        templet: '<span><i class="layui-icon layui-icon-chart pd"></i> 采食历史</span>'
                        ,id: 'feed_his'
                    }, {
                        templet: '<span><i class="layui-icon layui-icon-list pd"></i> 设置记录</span>'
                        ,id: 'op_his'
                    }, {
                        templet: '<span><i class="layui-icon layui-icon-release pd"></i> 远程控制</span>'
                        ,id: 'manul'
                    }, 
                    // {
                    //     templet: '<span><i class="layui-icon layui-icon-note pd"></i> 猪只管理</span>'
                    //     ,id: 'pig'
                    // }, 
                    {
                        templet: '<span><i class="layui-icon layui-icon-form pd"></i> 详细</span>'
                        ,id: 'detail'
                    }];

                dropdown.render({
                    elem: '.action-btn'
                    ,className: 'site-dropdown-demo'
                    ,data:menuData 
                    ,click: function(data, othis){
                        var elem = $(this.elem)
                        ,sn = elem.data('sn'); //表格列表的预埋数据
                        //layer.msg('得到表格列表的 sn：'+ sn +'，下拉菜单 id：'+ data.id);
                        var item = null;
                        for(var i=0;i<allData.length;i++){
                            if(allData[i].sn == sn){
                                item = allData[i];
                                break;
                            }
                        }
                        console.info(item);
                        if(data.id == 'feed_his'){
                            onFeedHis(item);
                        }else if (data.id == 'op_his'){
                            onOpHis(item);
                        }else if (data.id == 'manul'){
                            onManul(item);
                        }else if (data.id == 'pig'){
                            onPig(item);
                        }else if (data.id == 'detail'){
                            onDetail(item);
                        }
                    }
                });

                setTimeout(function(){
                    $(".layui-table-main tr").each(function (index, val) {
                        var h = $(val).height();
                        console.info(h);
                        $(".layui-table-fixed").each(function () {
                            $($(this).find(".layui-table-body tbody tr")[index]).height(h);
                        });
                        $(val).height(h);
                    });
                    $(".layui-table-header tr").each(function (index, val) {
                        var h = $(val).height();
                        //console.info(h);
                        $(".layui-table-fixed").each(function () {
                            $($(this).find(".layui-table-header thead tr")[index]).height(h);
                        });
                        $(val).height(h);
                    });

                    
                },500);

                
                

                auto_hnum = false;//每次渲染完成，关闭自动生成栏位号

                for(var i=0;i<actions.length;i++){
                    $('.action-'+actions[i].action_id).removeClass("layui-hide");
                }
                var that = this.elem.next();
                
                res.data.forEach(function (item, index) {
                    //console.log(item.empName);item表示每列显示的数据
                    /*if (!item.online) {
                        var tr = that.find(".layui-table-box tbody tr[data-index='" + (index-1) + "']").css("color", "#a08370");
                    } else {
                        //var tr = that.find(".layui-table-box tbody tr[data-index='" + index + "']").css("background-color", "#fff");
                        if(item.mode==0){
                            var tr = that.find(".layui-table-box tbody tr[data-index='" + (index-1) + "']").css("color", "#323a41");
                            console.info(tr);
                            console.info(item,index);
                        }
                        if(item.alarm){
                            var tr = that.find(".layui-table-box tbody tr[data-index='" + (index-1) + "']").css("color", "#d75814");
                        }
                    }*/
                    let tips_index=0
                    $('#nowater-tip-'+item.sn).mouseover(function(){
                        tips_index=layer.tips('无余料','#nowater-tip-'+item.sn,{
                            tips:[1, '#111'],
                            time: 9999000,
                            area: ['80px', 'auto']
                        });
                    })
            
                    $('#nowater-tip-'+item.sn).mouseout(function(){
                        layer.close(tips_index);
                    });

                    $('#water-tip-'+item.sn).mouseover(function(){
                        tips_index=layer.tips('有余料','#water-tip-'+item.sn,{
                            tips:[1, '#1E9FFF'],
                            time: 9999000,
                            area: ['80px', 'auto']
                        });
                    })
                    $('#water-tip-'+item.sn).mouseout(function(){
                        layer.close(tips_index);
                    });

                    $('#calFeed-tip-'+item.sn).mouseover(function(){
                        tips_index=layer.tips('未进行下料校准，请及时校准保证下料准确性!','#calFeed-tip-'+item.sn,{
                            tips:[1, '#111'],
                            time: 9999000,
                            area: ['200px', 'auto']
                        });
                    })
                    $('#calFeed-tip-'+item.sn).mouseout(function(){
                        layer.close(tips_index);
                    });

                    
                    /*if(item.alarm){
                        if(item.alarm==1){
                            alarm_arr.push("堵料");
                        }else if(item.alarm==2){
                            alarm_arr.push("堵水");
                        }else if(item.alarm==3){
                            alarm_arr.push("堵料水");
                        }else{
                        }

                    }
                    if(item.alarm_ext){
                        alarm_arr.push("空转");
                    }*/

                    var alarm_arr=[];
                    var bin_alarm = getBinStr(item.alarm);
                    console.info("bin_alarm",bin_alarm);

                    if(getByteBit(item.alarm,0)>0){
                        alarm_arr.push("电机堵塞\n");
                    }
                    if(getByteBit(item.alarm,1)>0){
                        alarm_arr.push("出水堵塞\n");
                    }
                    if(getByteBit(item.alarm,2)>0){
                        alarm_arr.push("探针异常\n");
                    }
                    if(getByteBit(item.alarm,3)>0){
                        alarm_arr.push("触碰异常\n");
                    }
                    if(getByteBit(item.alarm,4)>0){
                        alarm_arr.push("电机异常\n");
                    }
                    if(getByteBit(item.alarm,5)>0){
                        alarm_arr.push("下水异常\n");
                    }
                    if(getByteBit(item.alarm,6)>0){
                        alarm_arr.push("电机空转\n");
                    }
                    /*if(item.alarm_ext){
                        alarm_arr.push("空转");
                    }*/

                    var alarm_str ="";
                    if(alarm_arr.length>0){
                        alarm_str = alarm_arr.join(",");
                    }

                    $('#alarm-tip-'+item.sn).mouseover(function(){
                        tips_index=layer.tips(alarm_str,'#alarm-tip-'+item.sn,{
                            tips:[1, '#FF5722'],
                            time: 9999000,
                            area: ['150px', 'auto']
                        });
                    })
                    $('#alarm-tip-'+item.sn).mouseout(function(){
                        layer.close(tips_index);
                    });

                });

                

                //初演示
                dropdown.render({
                    elem: '#hnum_menu_hint'
                    ,data: [{
                    title: '<span class="layui-text-xs">自动填写所有</span>'
                        ,id: 100
                    }]
                    ,className: 'site-dropdown-demo'
                    ,click: function(obj){
                        console.info(obj);
                        //layer.tips('点击了：'+ obj.title, this.elem, {tips: [1, '#5FB878']})
                        if(obj.id==100){
                            
                            /*lay_index = layer.open({
                                //area: 'auto',
                                area:['400px','250px'],
                                type: 1,
                                shade: 0.3,
                                offset: '15%',
                                shadeClose:true,
                                title: '设计行列', //不显示标题
                                content: $('#form_auto_hnum'), //捕获的元素，注意：最好该指定的元素要存放在body最外层，否则可能被其它的相对元素所影响
                                btn: ['确定', '取消']
                                ,yes: function(index, layero){
                                    lay_index=index;
                                    var submit = layero.find("#btn_auto_hnum");
                                    submit.click();
                                }
                            });*/
                            autoSetHnum();
                        }
                    }
                });

                var total = allData.length;
                var offline = 0;
                var disable = 0;
                var alarm = 0;

                var total_feed = 0;
                var total_feed_target=0;

                var active_day_num = 0;
                var day_sum = 0;
                var avg_day = 0;

                //console.info(allData);
                for(var i=0;i<allData.length;i++){
                    var item = allData[i];
                    if(!item.online||item.online=='0'){
                        offline++;
                    }
                    if(item.mode==0){
                        disable++;
                    }

                    if(item.online && item.mode!=0){
                        active_day_num++;
                        day_sum+=parseInt(item.day);
                        var feed = parseFloat(item.day_use_feed_auto)+parseFloat(item.day_use_feed_man);
                        total_feed+=feed;
                        total_feed_target+=parseFloat(item.max_feed);
                    }

                    if(item.alarm || item.alarm_ext || !item.online || item.online=="0"){
                        alarm++;
                    }

                    
                }

                var per = total_feed / total_feed_target * 100;
                var total_str = parseFloat(total_feed.toFixed(2).toString()).toString()+"/"+ parseFloat(total_feed_target.toFixed(2)).toString() +" kg";
                
                var per_str="";
                if(total_feed_target>0){
                    per_str="("+parseFloat(per.toFixed(1)).toString()+"%)";
                }else{
                    per_str="";
                }

                //日龄
                if(active_day_num>0){
                    avg_day = day_sum/active_day_num;
                    console.info("day_sum",day_sum);
                    console.info("active_day_num",active_day_num);
                    $("#id-day").html(parseInt(avg_day)) ;
                }else{
                    $("#id-day").html("N/A") ;
                }

                //猪只数量
                $("#id-pig").html(pig_num_total) ;

                //计算头均采食
                var pig_feed_avg = 'N/A';
                if(pig_num_total>0){
                    pig_feed_avg = parseFloat(total_feed/pig_num_total).toFixed(2).toString()
                }else{

                }
                $("#id-avg").html(pig_feed_avg+" kg") ;

                $('#id-housename').html(farmname+' '+ housename);
                $("#id-total").html(total);
                $("#id-offline").html(offline);
                $("#id-disable").html(disable);
                $("#id-alarm").html(alarm);

                $(".house-tip").hide();
                //提示未校准
                if(calFeedErr){
                    $("#id-calFeedErr").show();
                }

                //提示猪群异常
                if(house_type==3||house_type==4){
                    if(dfxw_id!=""){
                        var err = false;
                        var errStr="";
                        if(dfxw_unit_day_age!=-127){
                            //平均日龄
                            var day_diff =Math.abs(avg_day - dfxw_unit_day_age);
                            var rate = parseFloat(day_diff)/parseFloat(avg_day);
                            console.info("avg_day",avg_day);
                            console.info("dfxw_unit_day_age",dfxw_unit_day_age);
                            console.info("day_diff",day_diff);
                            console.info("rate",rate);
                            if(rate>0.05){
                                err = true;
                                errStr += '日龄差异:'+dfxw_unit_day_age+'/'+parseInt(avg_day)+"<br>";
                                
                            }
                        }
                        if(dfxw_unit_num!=-127){
                            //猪只数量
                            var pig_num_diff =Math.abs(pig_num_total - dfxw_unit_num);
                            var rate = parseFloat(pig_num_diff)/parseFloat(pig_num_total);
                            console.info("pig_num_total",pig_num_total);
                            console.info("dfxw_unit_num",dfxw_unit_num);
                            console.info("pig_num_diff",pig_num_diff);
                            console.info("rate",rate);
                            if(rate>0.05){
                                err = true;
                                errStr += '猪只差异:'+dfxw_unit_num+'/'+pig_num_total+"<br>";
                            }
                        }
                        if(err){
                            $("#id-dfxwBizErr").show();
                            $('#id-dfxwBizErr').mouseover(function(){
                                tips_index=layer.tips(errStr,'#id-dfxwBizErr',{
                                    tips:[1, '#111'],
                                    time: 9999000,
                                    area: ['200px', 'auto']
                                });
                            });
                            $('#id-dfxwBizErr').mouseout(function(){
                                layer.close(tips_index);
                            });
                        }
                    }
                }
                

                //自由采食不显示目标
                if(house_type==3||house_type==4){
                    $("#id-sum").html(parseFloat(total_feed.toFixed(2).toString()).toString()+" kg") ;
                }else{
                    $("#id-sum").html(  total_str+per_str) ;
                }

                //只有妊娠才显示分娩按钮
                if(house_type==1){
                    $("#btn_born").show();
                }else{
                    $("#btn_born").hide();
                }

                //获取方案参数
                var feed_plan_id_arr = [];
                for(var i=0;i<allData.length;i++){
                    if(allData[i].feed_plan_id){
                        var feed_plan_id = allData[i].feed_plan_id;
                        feed_plan_id_arr.push(feed_plan_id);
                    }
                }

                if(feed_plan_id_arr.length>0){
                    var ids = feed_plan_id_arr.join(",");
                    console.info("plan ids",ids)
                    $.ajax({
                        type: 'get',
                        url: '../Api/FeedPlanNew',
                        data: {id:ids},
                        beforeSend: function(request) {
                            request.setRequestHeader("Authorization", 'Bearer '+window.localStorage.getItem("token"));
                        },
                        dataType: "json",
                        success: function (res) {
                            if(res.code>=0){
                                allPlanData = res.data;
                                if(allPlanData.length>0){
                                    
                                    for(var i=0;i<allData.length;i++){
                                        if(allData[i].para){

                                            var plan = null;
                                            for(var x=0;x<allPlanData.length;x++){
                                                if(allPlanData[x].id == allData[i].feed_plan_id){
                                                    plan = allPlanData[x];
                                                }
                                            }
                                            if(plan){
                                                
                                                var planNodePara =JSON.parse(plan.para);
                                                delete planNodePara.Pg_rev_bits;
                                                delete planNodePara.La_rev_bits;
                                                delete planNodePara.Nr_flag_bits;
                                                delete planNodePara.Fat_flag_bits;
                                                delete planNodePara.Tmr_flag_bits;
                                                delete planNodePara.ReverseTimes;
                                                delete planNodePara.ReverseTurns;
                                                //delete planNodePara.WaterDelay;
                                                //delete planNodePara.PtTimeDelay;
                                                //delete planNodePara.CurIdle;
                                                delete planNodePara.TbPTime;
                                                //console.info("planNodePara",planNodePara);

                                                var nodePara = JSON.parse(allData[i].para);
                                                delete nodePara.Pg_rev_bits;
                                                delete nodePara.La_rev_bits;
                                                delete nodePara.Nr_flag_bits;
                                                delete nodePara.Fat_flag_bits;
                                                delete nodePara.Tmr_flag_bits;
                                                delete nodePara.ReverseTimes;
                                                delete nodePara.ReverseTurns;
                                                //delete nodePara.WaterDelay;
                                                //delete nodePara.PtTimeDelay;
                                                //delete nodePara.CurIdle;
                                                delete nodePara.TbPTime;
                                                //console.info("nodePara",nodePara);
                                                console.info("planNodePara CalAD",planNodePara.CalAD);
                                                console.info("nodePara CalAD",nodePara.CalAD);
                                                console.info("planNodePara CalADR",planNodePara.CalADR);
                                                console.info("nodePara CalADR",nodePara.CalADR);
                                                /*var same = true;
                                                if(nodePara.Mode == planNodePara.Mode){
                                                    if(nodePara.Mode==1 || nodePara.Mode==2){
                                                        //妊娠 哺乳
                                                        for(var x=0;x<nodePara.Pg_gday.length;x++){
                                                            if(nodePara.Pg_gday[x]!=planNodePara.Pg_gday[x]){
                                                                same = false;
                                                                console.info("nodePara.Pg_gday[x]=",nodePara.Pg_gday[x]);
                                                                console.info("planNodePara.Pg_gday[x]=",planNodePara.Pg_gday[x]);
                                                                break
                                                            }
                                                        }

                                                        for(var x=0;x<nodePara.Pg_startT.length;x++){
                                                            for(var y=0;y<nodePara.Pg_startT[x].length;y++){
                                                                if(nodePara.Pg_startT[x][y]!=planNodePara.Pg_startT[x][y]){
                                                                    same = false;
                                                                    console.info("nodePara.Pg_startT[x][y]=",nodePara.Pg_startT[x][y]);
                                                                    console.info("planNodePara.Pg_startT[x][y]=",planNodePara.Pg_startT[x][y]);
                                                                    break
                                                                }
                                                            }
                                                        }

                                                        for(var x=0;x<nodePara.Pg_endT.length;x++){
                                                            for(var y=0;y<nodePara.Pg_endT[x].length;y++){
                                                                if(nodePara.Pg_endT[x][y]!=planNodePara.Pg_endT[x][y]){
                                                                    same = false;
                                                                    console.info("nodePara.Pg_endT[x][y]=",nodePara.Pg_endT[x][y]);
                                                                    console.info("planNodePara.Pg_endT[x][y]=",planNodePara.Pg_endT[x][y]);
                                                                    break
                                                                }
                                                            }
                                                        }

                                                        for(var x=0;x<nodePara.Pg_endT.length;x++){
                                                            for(var y=0;y<nodePara.Pg_endT[x].length;y++){
                                                                if(nodePara.Pg_endT[x][y]!=planNodePara.Pg_endT[x][y]){
                                                                    same = false;
                                                                    console.info("nodePara.Pg_endT[x][y]=",nodePara.Pg_endT[x][y]);
                                                                    console.info("planNodePara.Pg_endT[x][y]=",planNodePara.Pg_endT[x][y]);
                                                                    break
                                                                }
                                                            }
                                                        }
                                                    }
                                                }

                                                console.info("same=",same);
                                                */

                                                
                                                var Sn = nodePara.Sn;
                                                var Mode = nodePara.Mode;
                                                var Passwd = nodePara.Passwd;
                                                var Gday = nodePara.Gday;
                                                var Hnum = nodePara.Hnum;
                                                var Col = nodePara.Col;
                                                var Row = nodePara.Row;
                                                var Hnum = nodePara.Hnum;
                                                var HnumVal = nodePara.HnumVal;
                                                var IdleCur = nodePara.IdleCur;
                                                var Crc16 = nodePara.Crc16;
                                                var CalFeed = nodePara.CalFeed;

                                                planNodePara.Sn = Sn;
                                                planNodePara.Mode = Mode;
                                                planNodePara.Passwd = Passwd;
                                                planNodePara.Gday = Gday;
                                                planNodePara.Hnum = Hnum;
                                                planNodePara.Col = Col;
                                                planNodePara.Row = Row;
                                                planNodePara.HnumVal = HnumVal;
                                                planNodePara.IdleCur = IdleCur;
                                                planNodePara.Crc16 = Crc16;
                                                planNodePara.CalFeed = CalFeed;


                                                nodePara.Pg_flag=[];
                                                planNodePara.Pg_flag=[];
                                                nodePara.La_flag=[];
                                                planNodePara.La_flag=[];
                                                nodePara.Fat_flag=[];
                                                planNodePara.Fat_flag=[];
                                                nodePara.Nr_flag=[];
                                                planNodePara.Nr_flag=[];
                                                nodePara.Tmr_flag=[];
                                                planNodePara.Tmr_flag=[];

                                                nodePara.Pg_rev=[];
                                                planNodePara.Pg_rev=[];
                                                nodePara.La_rev=[];
                                                planNodePara.La_rev=[];
                                                nodePara.Fat_rev=[];
                                                planNodePara.Fat_rev=[];
                                                nodePara.Nr_rev=[];
                                                planNodePara.Nr_rev=[];




                                                const sortPlanNodePara = { }; // 排序后的对象
                                                Object.keys(planNodePara).sort().map(key => {
                                                    sortPlanNodePara[key] = planNodePara[key]
                                                });

                                                const sortNodePara = { }; // 排序后的对象
                                                Object.keys(nodePara).sort().map(key => {
                                                    sortNodePara[key] = nodePara[key]
                                                });

                                                var planNodeParaStr = JSON.stringify(sortPlanNodePara).replaceAll('""','"0"');
                                                var nodeParaStr = JSON.stringify(sortNodePara).replaceAll('""','"0"');
                                                planNodeParaStr = planNodeParaStr.replaceAll('.0"','"');
                                                nodeParaStr = nodeParaStr.replaceAll('.0"','"');
                                                if(planNodeParaStr==nodeParaStr){
                                                    //console.info("参数一致");
                                                }else{
                                                    console.error("参数不一致:",Hnum,Sn);
                                                    console.info("planNodeParaStr",planNodeParaStr);
                                                    console.info("nodeParaStr",nodeParaStr);
                                                    $("#plan-"+Sn).removeClass("layui-text-blue").addClass("layui-text-orange");
                                                    // $("#plan-"+Sn).append(" <i class='layui-icon layui-icon-tips'></i>");
                                                }

                                            }
                                            

                                            
                                        }
                                    }
                                }
                                
                            }else{

                                layer.alert(res.msg);
                            }
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            layer.msg('读取设备参数失败');
                        },
                        complete: function(XMLHttpRequest, textStatus) {
                            layer.closeAll('loading');
                        },
                    });
                }

                setTimeout(function(){ window.dispatchEvent(new Event('resize'))},200);
            }
        };

        table.on('sort(table)', function(obj){
            table.reload('table', {
                initSort: obj //记录初始排序，如果不设的话，将无法标记表头的排序状态。
                ,where: { //请求参数（注意：这里面的参数可任意定义，并非下面固定的格式）
                    //order_field: obj.field //排序字段
                    //,order_type: obj.type //排序方式
                    order:obj.field+" "+(obj.type||"")
                }
            });
        });

        //监听行工具事件
        table.on('tool(table)', function(obj){
            var data = obj.data;
            console.info(obj)
            /*if(obj.event === 'earmark'){
                console.info('earmark')
                onEarmark(data);
            }else if(obj.event === 'pig_type'){
                console.info('pig_type')
                onPigType(data);
            }*/
            if(obj.event === 'pig'){
                onPig(data)
            }else if(obj.event === 'detail'){
                console.info('detail')
                if(data.device_type=="DMXFGW"){
                    onDetail(data)
                }else if(data.device_type=="HZFGW"){
                    onDetail(data);
                }
                
            }else if(obj.event === 'feed_his'){
                onFeedHis(data)
            }else if(obj.event === 'op_his'){
                onOpHis(data)
            }else if(obj.event === 'feed_plan'){
                onFeedPlan(data)
            }else if(obj.event === 'manul'){
                onManul(data)
            }
        });

        table.on('edit(table)', function(obj){ //注：edit是固定事件名，test是table原始容器的属性 lay-filter="对应的值"
            console.log(obj.value); //得到修改后的值
            console.log(obj.field); //当前编辑的字段名
            console.log(obj.data); //所在行的所有相关数据
            if(obj.field=="pig_num"){
                //修改猪只个数
                var item={
                    sn:obj.data.sn,
                    pig_num:obj.value,
                    son:0,
                };
                layer.load(1);
                $.ajax({
                    type: "PUT",
                    url: '../Api/Pig/PigNum',
                    data: item,
                    beforeSend: function(request) {
                        request.setRequestHeader("Authorization", 'Bearer '+window.localStorage.getItem("token"));
                    },
                    dataType: "json",
                    success: function (res) {
                        if(res.code>=0){
                            layer.close(lay_index);
                            toastr.success("修改猪只数成功");
                            //search();
                        }else{
                            toastr.warning(res.msg, "异常");
                        }
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        layer.msg('加载信息失败');
                    },
                    complete: function(XMLHttpRequest, textStatus) {
                        layer.closeAll('loading');
                    },

                });
            }else if(obj.field=="son"){
                //修改猪只个数
                var item={
                    sn:obj.data.sn,
                    pig_num:1,
                    son:obj.value,
                };
                layer.load(1);
                $.ajax({
                    type: "PUT",
                    url: '../Api/Pig/PigNum',
                    data: item,
                    beforeSend: function(request) {
                        request.setRequestHeader("Authorization", 'Bearer '+window.localStorage.getItem("token"));
                    },
                    dataType: "json",
                    success: function (res) {
                        if(res.code>=0){
                            layer.close(lay_index);
                            toastr.success("修改仔猪数成功");
                            //search();
                        }else{
                            toastr.warning(res.msg, "异常");
                        }
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        layer.msg('加载信息失败');
                    },
                    complete: function(XMLHttpRequest, textStatus) {
                        layer.closeAll('loading');
                    },

                });
            }
            
        });
        
        

        layer.load(1);
        getNodes(obj).then(function(res) {
            layer.closeAll("loading");
            if(res.code>=0){
                var list = res.data;
                if(auto_hnum){
                    /*for(var i=0;i<list.length;i++){
                        let num = list[i].tn+1
                        if(num<10){
                            new_hnum = "00"+num.toString()
                        }else if(num<100){
                            new_hnum = "0"+num.toString()
                        }else{
                            new_hnum = num.toString()
                        }
                        new_hnum = "A"+new_hnum
                        list[i].hnum = new_hnum;
                    }*/

                    
                    //var ascii_code = auto_hnum_prefix_idx.charCodeAt(0);

                    for(var i=0;i<list.length;i++){
                        let num = list[i].tn;
                        //var row_idx = Math.floor(num/auto_hnum_col);
                        //var col_idx = num%auto_hnum_col;
                        //console.info(num,row_idx,col_idx);

                        //var prefix = String.fromCharCode(ascii_code+row_idx);
                        //var col_str = (col_idx+1).toString().padStart(3,"0");
                        //console.info(i,row_idx,col_idx,prefix,col_str);
                        var new_hnum = list[i].tn+1;
                        list[i].hnum = new_hnum;
                    }
                }
                tableOptions.data = list;
                table.render(tableOptions);
                layer.close(lay_index);
                //toastr.info("栏位号已经填写，请确认无误后勾选下发到饲喂器")
            }
            auto_hnum = false;
        });
    }

    function getNodes(para){
        console.info("para",para);
        var promise = new Promise(function(resolve, reject) {
            $.ajax({
                type: 'GET',
                url: "../Api/Device/Feednode",
                data: para,
                beforeSend: function(request) {
                    request.setRequestHeader("Authorization", 'Bearer '+window.localStorage.getItem("token"));
                },
                success: function (data) {

                    if (data && data.code>=0) {
                        resolve(data);
                    }else{
                        resolve(data);
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    reject(err);
                },
                complete: function(XMLHttpRequest, textStatus) {

                },
                dataType: "json"
            });
        });
        return promise;
    }


    function showPlanTable(){
        renderGroupSelect();
        renderFarmSelect();


        Table1 = table.render({
            elem: '#table_plan'
            //,data:data
            ,url:'../Api/FeedPlanNew/Page'
            ,height: '400'
            ,method:'GET'
            ,headers : {'Authorization': 'Bearer '+window.localStorage.getItem("token")}
            ,where: {model:node_model}
            ,page: true
            ,limit:30
            //,toolbar: '#table_toolbar' //开启头部工具栏，并为其绑定左侧模板
            ,defaultToolbar: ['']
            ,title: ''
            ,even:false
            ,size: 'sm' //小尺寸的表格
            //,skin: 'nob' //无框风格
            ,cols: [[
                {type: 'radio',title:'勾选'}
                /*,{field:'', title:'集团/场区',  sort: true, templet: function(d) {
                            var html = "";
                            if(d.global){
                                return "<span lay-event=\"view\" class='layui-text-xs hand layui-text-orange'><i class='layui-text-xs layui-icon layui-icon-diamond'></i>  "+  "系统"+"   </span>";
                            }
                            else{
                                if(d.farmname){
                                    html = d.farmname;
                                }else{
                                    if(d.farmid){
                                        if(d.farmid==0){
                                            html = "集团";
                                        }
                                        else{
                                            html = "未知";
                                        }
                                    }
                                    else{
                                        //html = "待补充设置";
                                        html="<span class='mr-left-md '>待补充设置 <i id='id-tip-"+d.id+"' class='layui-icon layui-icon-tips layui-text-xs  layui-text-orange'></i></span>";
                                    }
                                }
                            }
                            
                            return html;
                        }}*/
                ,{field:'group_name', title:'集团',  sort: true, templet: function(d) {
                    var html = "";
                    if(!d.group_code){
                        return "";
                        
                    }else{
                        return "<span lay-event=\"\" class='layui-text-xs hand'>"+  d.group_name+"</span>";
                    }
                    return html;
                }}
                ,{field:'farmname', title:'场区',  sort: true, templet: function(d) {
                    var html = "";
                    if(!d.farmid){
                        return "";
                        
                    }else{
                        return "<span lay-event=\"\" class='layui-text-xs hand'>"+  d.farmname+"</span>";
                    }
                    return html;
                }}
                ,{field:'name', title:'名称',  sort: true, templet: function(d) {
                            var html = "";
                            if(d.global){
                                return "<span lay-event=\"view\" class='layui-text-xs hand layui-text-orange'><i class='layui-text-xs layui-icon layui-icon-diamond'></i>  "+  d.name+"   </span>";
                            }else{
                                return "<span lay-event=\"view\" class='layui-text-xs hand '>"+  d.name+"<i class=''></i> </span>";
                            }
                            return html;
                        }}
                    // ,{field:'food_type', title:'饲料类型',width:100, sort: true}
                    // ,{field:'food_plan', title:'饲料方案',width:100, sort: true}
                    ,{field:'remark', title:'备注', sort: false}
                    ,{field:'', title:'类型',width:100, sort: false,align:'center', templet: function(d) {
                        var model = "";
                        if(d.model && d.model=="fg"){
                            model = "<span class='layui-badge-rim'>"+"粥料器 "+"</span>";
                        }else{
                            model = "<span class='layui-badge-rim'>"+"饲喂器 "+"</span>";
                        }
                        return model;
                    }}
                    ,{field:'create_user_name', title:'创建人', width:100, sort: false}
                    //,{field:'create_date', title:'创建时间',width:140,align:'center', sort: true}
                    ,{field:'update_user_name', title:'修改人',width:100, sort: false}
                    //,{field:'update_date', title:'修改时间',width:140,align:'center', sort: true}
                    ,{field:'', title:'操作', width:80,sort: false,align:'left',fixed: 'right', templet: function(d) {
                            var html = "";
                            html += "<a href='#'   class=\"\" lay-event=\"view\"><span class=\" layui-text-orange \">预览</span></a>";
                            return html;
                        }}
            ]]
        });

        table.on('sort(table_plan)', function(obj){
            table.reload('table_plan', {
                initSort: obj //记录初始排序，如果不设的话，将无法标记表头的排序状态。
                ,where: { //请求参数（注意：这里面的参数可任意定义，并非下面固定的格式）
                    //order_field: obj.field //排序字段
                    //,order_type: obj.type //排序方式
                    order:obj.field+" "+(obj.type||"")
                }
            });
        });

        table.on('tool(table_plan)', function(obj){
            var data = obj.data;
            switch(obj.event){
                case 'view':
                    onViewPlan(data);
                    break;
            };
        });
    }

    function showPigTable(obj){
        var height = '';
        if(obj.mode==2){
            //哺乳，带仔
            height = 190;
        }else{
            height = 220;
        }
        table.render({
            elem: '#table_pig'
            //,data:data
            ,url:'../Api/Pig'
            ,height: height
            ,method:'GET'
            ,headers : {'Authorization': 'Bearer '+window.localStorage.getItem("token")}
            ,where: {addr:obj.addr,sn:obj.sn}
            ,page: false
            ,limit:100000
            //,toolbar: '#table_toolbar' //开启头部工具栏，并为其绑定左侧模板
            ,defaultToolbar: ['']
            ,title: ''
            ,even:false
            ,size: 'sm' //小尺寸的表格
            //,skin: 'nob' //无框风格
            ,cols: [[
                {type: 'numbers',title:'序号', fixed: 'left'}
                //{field:'id', title:'ID', width:120, unresize: false, sort: true}
                ,{field:'earmark', title:'耳标号', sort: false}
                ,{field:'pig_type', title:'猪种', sort: false}
                ,{field:'weight', title:'重量(kg)', sort: false}
                ,{field:'', title:'', width:100,sort: false,align:'left',fixed: 'right', templet: function(d) {
                        var html = "";
                        html += "<a href='#'   class=\"layui-hide action-view\" lay-event=\"edit\"><span class=\"  layui-text-black text-underline\">修改</span></a><span class=\"shortGreyLine\"></span>";
                        html += "<a href='#'   class=\"layui-hide action-view\" lay-event=\"delete\"><span class=\"  layui-text-black text-underline\">删除 </span></a><span class=\"shortGreyLine layui-hide\"></span>";
                        return html;
                    }}
            ]]
            ,done: function(res, curr, count){
                for(var i=0;i<actions.length;i++){
                    $('.action-'+actions[i].action_id).removeClass("layui-hide");
                }
                var that = this.elem.next();
                //allData = res.data;
                var pig_num = res.count;
                if(pig_num>0){
                    $("#pig_num").val(pig_num);
                }
                res.data.forEach(function (item, index) {
                    //console.log(item.empName);item表示每列显示的数据
                });
            }
        });
        //监听行工具事件
        table.on('tool(table_pig)', function(obj){
            var data = obj.data;
            if(obj.event === 'edit'){
                console.info('edit')
                onPigItemEdit(data);
            }else if(obj.event === 'delete'){
                console.info('delete')
                onPigItemDelete(data);
            }
        })
    }

    function onDetail(item){
        var obj = item;
        console.info("obj",obj);

        tomorrow = moment().add(1,"days").format('YYYY-MM-DD');
        today = moment().format('YYYY-MM-DD');
        yestoday = moment().add(-1,"days").format('YYYY-MM-DD');
        aweekago = moment().add(-7,"days").format('YYYY-MM-DD');
        amonthago = moment().add(-30,"days").format('YYYY-MM-DD');
        

        var active = {
            set: function(othis){
                var THIS = 'layui-bg-normal'
                    ,key = othis.data('key')
                    ,options = {};

                othis.css('background-color', '#3c7cff').siblings().removeAttr('style');
                var val = othis.data('value');
                console.info("value",val);
                $(".div_his").addClass("layui-hide");
                $("."+val).removeClass("layui-hide");
            }
        };
        
        var active2 = {
            set: function(othis){
                var THIS = 'layui-bg-normal'
                    ,key = othis.data('key')
                    ,options = {};

                othis.css('background-color', '#3c7cff').siblings().removeAttr('style');
                var val = othis.data('value');
                console.info("value",val);
                $(".div_alarm").addClass("layui-hide");
                $("."+val).removeClass("layui-hide");
            }
        };

        /* chrome 不加入延时会绑定事件失败*/
        setTimeout(function () {
            $('.history_btns .layui-btn').off();
            $('.plan_btns .layui-btn').off();
            $('.alarm_btns .layui-btn').off();
            $('.history_btns .layui-btn').on('click', function(){
                //console.info("history_btns clicks")
                var othis = $(this), type = othis.data('type');
                //console.info(othis)
                active[type] ? active[type].call(this, othis) : '';
            });

            $('.plan_btns .layui-btn').on('click', function(){
                var othis = $(this), type = othis.data('type');
                active1[type] ? active1[type].call(this, othis) : '';
            });
            $('.alarm_btns .layui-btn').on('click', function(){
                var othis = $(this), type = othis.data('type');
                active2[type] ? active2[type].call(this, othis) : '';
            });
        },500);

        


        //耳标，猪种
        obj.earmark = obj.earmark ||'未设置';
        obj.pig_type = obj.pig_type ||'未设置';

        if(obj.online>0){
            $("#title_online").show();
            $("#title_offline").hide();
            if(obj.mode==0){
                $("#title_disable").show();
            }else{
                $("#title_disable").hide();
            }

            $("#title_ver").show();
            $("#title_ver").html("版本号:"+obj.version);
            $("#title_sn").show();
            $("#title_sn").html("SN:"+obj.sn);
            /*if(obj.alarm>0){
                $("#title_alarm").show();
                $("#title_alarm").html("告警:"+obj.AlarmStr);
            }else{
                $("#title_alarm").hide();
            }*/
        }else{
            $("#title_online").hide();
            $("#title_offline").show();
            $("#title_disable").hide();
            $("#title_sn").hide();
            $("#title_ver").hide();
            //$("#title_alarm").hide();
            //layer.alert("当前饲喂器离线");
        }

        //告警
        var alarm_arr=[];
        if(obj.alarm>0){
            var bin_alarm = getBinStr(obj.alarm);
            console.info("bin_alarm",bin_alarm);

            if(getByteBit(obj.alarm,0)>0){
                alarm_arr.push("电机堵塞\n");
            }
            if(getByteBit(obj.alarm,1)>0){
                alarm_arr.push("出水堵塞\n");
            }
            if(getByteBit(obj.alarm,2)>0){
                alarm_arr.push("探针异常\n");
            }
            if(getByteBit(obj.alarm,3)>0){
                alarm_arr.push("触碰异常\n");
            }
            if(getByteBit(obj.alarm,4)>0){
                alarm_arr.push("电机异常\n");
            }
            if(getByteBit(obj.alarm,5)>0){
                alarm_arr.push("下水异常\n");
            }
        }else{
            
        }

        if(obj.alarm_ext){
            alarm_arr.push("空转");
        }

        if(alarm_arr.length>0){
            $("#title_alarm").show();
            $("#title_alarm").html("告警:"+alarm_arr.join(","));
        }else{
            $("#title_alarm").hide();
        }

        //obj.mode = decodeMode(obj.mode);
        if(obj.device_type){
            if(obj.device_type=="HZFGW"){
                obj.mode = decodeMode(obj.mode);
            }else if(obj.device_type=="DMXFGW"){
                obj.mode = decodeModeNew(obj.mode);
            }
        }

        // if(obj.free_feed){
        //     obj.mode+=(" (自由采食)");
        // }else{
        //     obj.mode+=(" (定时定量)");
        // }

        // if(obj.feed_water==0){
        //     obj.feed_water="不出水";
        // }else if(obj.feed_water==1){
        //     obj.feed_water="1:1";
        // }else if(obj.feed_water==2){
        //     obj.feed_water="1:2";
        // }else if(obj.feed_water==3){
        //     obj.feed_water="1:3";
        // }else if(obj.feed_water==4){
        //     obj.feed_water="1:4";
        // }else if(obj.feed_water==4){
        //     obj.feed_water="1:5";
        // }

        //$("#form_status")[0].reset();
        

        layer.open({
            //area: 'auto',
            area:['650px','500px'],
            //area:['70%','80%'],
            offset: '10%',
            shade: 0.5,
            shadeClose: true,
            type: 1,
            title: obj.housename+" "+obj.hnum, //不显示标题
            content: $('#detail'), //捕获的元素，注意：最好该指定的元素要存放在body最外层，否则可能被其它的相对元素所影响
            maxmin: false,
            btn: ['确定'],
            yes: function(index, layero){
                //点击确认触发 iframe 内容中的按钮提交
                lay_index=index;
                layer.close(lay_index);
            }
        });

        $.ajax({
            type: 'get',
            url: '../Api/Device/Feednode',
            data: {sn:item.sn,addr:item.addr},
            beforeSend: function(request) {
                request.setRequestHeader("Authorization", 'Bearer '+window.localStorage.getItem("token"));
            },
            dataType: "json",
            success: function (res) {
                if(res.code>=0){
                    list = res.data;
                    //console.info(list);
                    if(list.length>0){
                        var para = JSON.parse(list[0].para);
                        var status = JSON.parse(list[0].status);

                        console.info("Adval:",status.Adval);
                        console.info("有余料SSD值:",para.CalAD);
                        console.info("无余料SSD值:",para.CalADR);
                        //console.info("余料检测:",para.YlCheck[obj.mode - 1]);
                        if(para.YlCheck && para.YlCheck[obj.mode - 1]>0){
                            if(parseInt(para.CalADR)<parseInt(status.Adval)){
                                obj.other="无水";
                            }else if(parseInt(para.CalAD)>parseInt(status.Adval)){
                                obj.other="有水";
                            }else{
                                obj.other="";
                            }
                        }else{
                            obj.other="";
                        }

                        //运行时间统计
                        if(list[0].first_online){
                            let dura = moment().unix() - moment(list[0].first_online).unix();
                            console.info("dura=",dura);
                            console.info("moment().format('x')=",moment().unix());
                            console.info("moment(obj.first_online).format('x')=",moment(list[0].first_online).unix());
                            var dura_str = beautyTimeSpan(dura);
                            console.info("dura_str=",dura_str);
                            //obj.dura_str = dura_str;
                            $("#title_dura").html("运行:"+dura_str);
                        }

                        console.info("obj",obj);
                        form.val("form_status",obj);
                        
                    }
                    resize();
                    
                }else{

                    layer.alert(res.msg);
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                layer.msg('读取设备参数失败');
            },
            complete: function(XMLHttpRequest, textStatus) {
                layer.closeAll('loading');
            },
        });




        var val = (formatFloat(obj.day_use_feed_auto,2)+formatFloat(obj.day_use_feed_man,2)).toFixed(2)+"/"+ obj.max_feed;
        var per = 0;
        if(obj.max_feed>0){
            var per = (formatFloat(obj.day_use_feed_auto,2)+formatFloat(obj.day_use_feed_man,2))/formatFloat(obj.max_feed,2) * 100;
        }

        element.progress('progress1', per.toFixed(1)+"%");


        
        
        

        //饲喂记录
        var query={sn:item.sn,addr:item.addr,begin:yestoday,end:tomorrow,begin_end:0,feed_type:1,tb_record:'0'};
        table.render({
            elem: '#table_feed_his'
            ,url: "../Api/History/FeedRecord"
            ,height: '250'
            ,method:'GET'
            ,headers : {'Authorization': 'Bearer '+window.localStorage.getItem("token")}
            ,where: query
            ,page: false
            /*,initSort: {
                field: 'hnum' //排序字段，对应 cols 设定的各字段名
                ,type: 'asc' //排序方式  asc: 升序、desc: 降序、null: 默认排序
            }*/
            ,limit:100000
            //,toolbar: '#table_toolbar' //开启头部工具栏，并为其绑定左侧模板
            ,defaultToolbar: ['']
            ,title: ''
            ,even:false
            ,size: 'sm' //小尺寸的表格
            //,skin: 'nob' //无框风格
            ,cols: [[
                //{type: 'checkbox', fixed: 'left'}
                //,fixed: 'left'
                //{field:'addr', title:'网关SN',width:100, sort: true}
                //,{field:'sn', title:'饲喂器SN',width:110, sort: true}
                //,{field:'hnum', title:'栏位号',width:90, sort: true}
                {field:'rectime', title:'记录时间',width:150, sort: true,templet: function(d){
                        var html = "";
                        html = moment(d.rectime).format("YYYY-MM-DD HH:mm:ss");
                        return html;
                    }}


                ,{field:'auto', title:'方式', sort: false,align:'center',templet: function(d){
                        var html="";
                        if(d.auto){
                            html="<span class=\"layui-text-green \" >自动</span>";
                        }else{
                            if(d.remote){
                                html="<span class=\"layui-text-orange\">远程手动</span>";
                            }else if(d.emergency){
                                html="<span class=\"layui-text-orange\">紧急手动</span>";
                            }
                            else{
                                html="<span class=\"layui-text-orange\">手动</span>";
                            }
                        }
                        return html;
                    }}


                //,{field:'event', title:'描述',width:110, sort: false,align:'left'}

                //,{field:'max_feed', title:'当天最大出料',width:110, sort: false,align:'right'}
                //,{field:'amount', title:'出料(kg)', sort: false,align:'right'}
                ,{field:'amount', title:'出料(kg)',width:100, sort: false,align:'right',templet: function(d){
                        if(d.begin_end==0 && d.feed_type==1 && d.amount==0){
                            return "<span class='layui-text-red'>"+ d.amount + "(空转)</span>";
                        }else{
                            return d.amount;
                        }
                    }}
                ,{field:'day_use_feed', title:'当日累计(kg)', sort: false,align:'right'}
                //,{field:'day_use_water', title:'累计出水(L)',width:100, sort: false,align:'right'}
                //,{field:'vin_calc', title:'输入电压',width:90, sort: false,align:'right'}
                //,{field:'motor_vol', title:'电机电压',width:90, sort: false,align:'right'}
                ,{field:'motor_cur', title:'电机电流', sort: false,align:'right'}

            ]]
        });

        //下水记录
        var query={sn:item.sn,addr:item.addr,begin:yestoday,end:tomorrow,begin_end:0,feed_type:0,tb_record:'0'};
        table.render({
            elem: '#table_water_his'
            ,url: "../Api/History/FeedRecord"
            ,height: '250'
            ,method:'GET'
            ,headers : {'Authorization': 'Bearer '+window.localStorage.getItem("token")}
            ,where: query
            ,page: false
            /*,initSort: {
                field: 'hnum' //排序字段，对应 cols 设定的各字段名
                ,type: 'asc' //排序方式  asc: 升序、desc: 降序、null: 默认排序
            }*/
            ,limit:100000
            //,toolbar: '#table_toolbar' //开启头部工具栏，并为其绑定左侧模板
            ,defaultToolbar: ['']
            ,title: ''
            ,even:false
            ,size: 'sm' //小尺寸的表格
            //,skin: 'nob' //无框风格
            ,cols: [[
                //{type: 'checkbox', fixed: 'left'}
                //,fixed: 'left'
                //{field:'addr', title:'网关SN',width:100, sort: true}
                //,{field:'sn', title:'饲喂器SN',width:110, sort: true}
                //,{field:'hnum', title:'栏位号',width:90, sort: true}
                {field:'rectime', title:'记录时间',width:150, sort: true,templet: function(d){
                        var html = "";
                        html = moment(d.rectime).format("YYYY-MM-DD HH:mm:ss");
                        return html;
                    }}


                ,{field:'auto', title:'方式', sort: false,align:'center',templet: function(d){
                        var html="";
                        if(d.auto){
                            html="<span class=\"layui-text-green \" >自动</span>";
                        }else{
                            if(d.remote){
                                html="<span class=\"layui-text-orange\">远程手动</span>";
                            }else{
                                html="<span class=\"layui-text-orange\">手动</span>";
                            }
                        }
                        return html;
                    }}


                //,{field:'event', title:'描述',width:110, sort: false,align:'left'}

                //,{field:'max_feed', title:'当天最大出料',width:110, sort: false,align:'right'}
                ,{field:'amount', title:'出水(L)', sort: false,align:'right'}
                //,{field:'day_use_feed', title:'当日累计(kg)', sort: false,align:'right'}
                ,{field:'day_use_water', title:'当日累计(L)', sort: false,align:'right'}
                //,{field:'vin_calc', title:'输入电压',width:90, sort: false,align:'right'}
                //,{field:'motor_vol', title:'电机电压',width:90, sort: false,align:'right'}
                //,{field:'motor_cur', title:'电机电流', sort: false,align:'right'}

            ]]
        });

        //触碰记录
        var query={sn:item.sn,addr:item.addr,begin:yestoday,end:tomorrow,tb_record:1,debug:2};
        table.render({
            elem: '#table_tb_his'
            ,url: "../Api/History/FeedRecord"
            ,height: '250'
            ,method:'GET'
            ,headers : {'Authorization': 'Bearer '+window.localStorage.getItem("token")}
            ,where: query
            ,page: false
            /*,initSort: {
                field: 'hnum' //排序字段，对应 cols 设定的各字段名
                ,type: 'asc' //排序方式  asc: 升序、desc: 降序、null: 默认排序
            }*/
            ,limit:100000
            //,toolbar: '#table_toolbar' //开启头部工具栏，并为其绑定左侧模板
            ,defaultToolbar: ['']
            ,title: ''
            ,even:false
            ,size: 'sm' //小尺寸的表格
            //,skin: 'nob' //无框风格
            ,cols: [[
                //{type: 'checkbox', fixed: 'left'}
                //,fixed: 'left'
                //{field:'addr', title:'网关SN',width:100, sort: true}
                //,{field:'sn', title:'饲喂器SN',width:110, sort: true}
                //,{field:'hnum', title:'栏位号',width:90, sort: true}
                {field:'rectime', title:'记录时间',width:150, sort: true,templet: function(d){
                        var html = "";
                        html = moment(d.rectime).format("YYYY-MM-DD HH:mm:ss");
                        return html;
                    }}


                // ,{field:'auto', title:'方式',width:70, sort: false,align:'center',templet: function(d){
                //         return d.auto?"<span class=\"layui-text-green \" >自动</span>":"<span class=\"layui-text-orange\">手动</span>";
                //     }}

                // ,{field:'feed_type', title:'类型',width:70, sort: false,align:'center',templet: function(d){
                //         return d.feed_type?"<span class=\"layui-text-orange-light \" >出料</span>":"<span class=\"layui-text-blue-light\">出水</span>";
                //     }}
                ,{field:'', title:'', sort: false,align:'left',templet: function(d){
                        return "<span class=\"layui-text-orange-light \" >触碰</span>";
                    }}

                //,{field:'max_feed', title:'当天最大出料',width:110, sort: false,align:'right'}
                //,{field:'amount', title:'出料水(kg/L)', sort: false,align:'right'}
                //,{field:'day_use_feed', title:'当日累计(kg)', sort: false,align:'right'}
                //,{field:'day_use_water', title:'当日累计(L)', sort: false,align:'right'}
                //,{field:'vin_calc', title:'输入电压',width:90, sort: false,align:'right'}
                //,{field:'motor_vol', title:'电机电压',width:90, sort: false,align:'right'}
                //,{field:'motor_cur', title:'电机电流', sort: false,align:'right'}

            ]]
        });

        //当前告警
        var query={sn:item.sn,addr:item.addr,status:"1",level:1};
        table.render({
            elem: '#table_alarm_now'
            //,data:data
            ,url:'../Api/Alarm/NowPage'
            ,height: '250'
            ,method:'GET'
            ,headers : {'Authorization': 'Bearer '+window.localStorage.getItem("token")}
            ,where: query
            ,page: false
            ,limit:100000
            //,toolbar: '#table_toolbar' //开启头部工具栏，并为其绑定左侧模板
            ,defaultToolbar: ['']
            ,title: ''
            ,even:true
            ,size: 'sm' //小尺寸的表格
            //,skin: 'nob' //无框风格
            ,cols: [[
                //{field:'sn', title:'SN', width:100,  sort: true},
                {field:'alarm_content', title:'告警内容',  sort: true,templet: function(d){
                        var html = "";
                        if(d.status==0){
                            html+="<span class=\"layui-text-green\">"+d.alarm_content+"</span> "
                        }else{
                            html+="<span class=\"layui-text-red\">"+d.alarm_content+"</span>"
                        }
                        return html;
                    }}
                ,{field:'add_time', title:'发生时间', width:200, sort: true}
            ]]
            ,done: function(res, curr, count){
                for(var i=0;i<actions.length;i++){
                    $('.action-'+actions[i].action_id).removeClass("layui-hide");
                }
                var that = this.elem.next();

            }
        });

        var query={sn:item.sn,addr:item.addr,begin:aweekago,end:tomorrow,level:1};
        table.render({
            elem: '#table_alarm_his'
            //,data:data
            ,url:'../Api/Alarm/Page'
            ,height: '250'
            ,method:'GET'
            ,headers : {'Authorization': 'Bearer '+window.localStorage.getItem("token")}
            ,where: query
            ,page: false
            ,limit:100000
            //,toolbar: '#table_toolbar' //开启头部工具栏，并为其绑定左侧模板
            ,defaultToolbar: ['']
            ,title: ''
            ,even:true
            ,size: 'sm' //小尺寸的表格
            //,skin: 'nob' //无框风格
            ,cols: [[
                //{field:'sn', title:'SN', width:100,  sort: true},
                {field:'status', title:'状态',width:80, sort: false,align:'center',templet: function(d){
                        var html = "";
                        if(d.status==0){
                            html+="<span class=\"layui-badge-dot layui-bg-blue\"></span> 已取消"
                        }else{
                            html+="<span class=\"layui-badge-dot layui-bg-red\"></span> 告警中"
                        }
                        return html;
                    }},
                {field:'alarm_content', title:'告警内容',  sort: true,templet: function(d){
                        var html = "";
                        if(d.status==0){
                            html+="<span class=\"layui-text-green\">"+d.alarm_content+"</span> "
                        }else{
                            html+="<span class=\"layui-text-red\">"+d.alarm_content+"</span>"
                        }
                        return html;
                    }}
                ,{field:'add_time', title:'发生时间', width:200, sort: true,templet: function(d){
                        var html = "";
                        html = moment(d.add_time).format("YYYY-MM-DD HH:mm:ss");
                        return html;
                    }}
                ,{field:'cancel_time', title:'取消时间', width:200, sort: true,templet: function(d){
                        var html = "";
                        html = moment(d.cancel_time).format("YYYY-MM-DD HH:mm:ss");
                        return html;
                    }}
            ]]
            ,done: function(res, curr, count){
                for(var i=0;i<actions.length;i++){
                    $('.action-'+actions[i].action_id).removeClass("layui-hide");
                }
                var that = this.elem.next();

            }
        });
    
    
    }

    function onOpHis(item){
        var obj = item;
        console.info("obj",obj);

        layer.open({
            //area: 'auto',
            area:['650px','500px'],
            //area:['70%','80%'],
            offset: '10%',
            shade: 0.5,
            shadeClose: true,
            type: 1,
            title: obj.housename+" "+obj.hnum+" 设置记录", //不显示标题
            content: $('#op_his'), //捕获的元素，注意：最好该指定的元素要存放在body最外层，否则可能被其它的相对元素所影响
            maxmin: false,
            btn: ['确定'],
            yes: function(index, layero){
                //点击确认触发 iframe 内容中的按钮提交
                lay_index=index;
                layer.close(lay_index);
            }
        });
        

        //方案日志
        var query={sn:item.sn,addr:item.addr,order:' time desc '};
        table.render({
            elem: '#table_op_log_set_para'
            ,url: "../Api/Log/OpLogPara"
            ,height: '280'
            ,method:'GET'
            ,headers : {'Authorization': 'Bearer '+window.localStorage.getItem("token")}
            ,where: query
            ,page: {
                limit:50,
                limits:[10, 20, 30, 40, 50,100,200,300,400],
                theme: '#3c7cff'
            }
            //,limit:100000
            //,toolbar: '#table_toolbar' //开启头部工具栏，并为其绑定左侧模板
            ,defaultToolbar: ['']
            ,title: ''
            ,even:false
            ,size: 'sm' //小尺寸的表格
            //,skin: 'nob' //无框风格
            ,cols: [[
                {type: 'numbers',title:'序号'}
                ,{field:'feed_plan_name', title:'方案名称', sort: true, templet: function(d) {
                        var html="";
                        var feed_plan_name = '';
                        
                        if(d.id){
                            if(d.feed_plan_name && d.feed_plan_name!=''){
                                feed_plan_name = d.feed_plan_name;
                                html+= "<span id=log-"+d.sn+" lay-event='paraLog' class='layui-text-xs hand layui-text-blue '>"+ feed_plan_name+"</span>";
                            }
                            else{
                                html+= "<span id=log-"+d.sn+" lay-event='paraLog' class='layui-text-xs hand layui-text-green '>保存设备参数</span>";
                            }
                        }
                        return html;
                    }}
                ,{field:'username', title:'操作人',width:110, sort: false}
                ,{field:'time', title:'操作时间',width:160, sort: true}
                ,{field:'res', title:'操作结果',width:110, sort: true}

            ]]
        });

        //监听行工具事件
        table.on('tool(table_op_log_set_para)', function(obj){
            var data = obj.data;
            console.info(obj)
            if(obj.event === 'paraLog'){
                onParaOpHisReadonly({id:data.id})
            }
        });

        query={sn:item.sn,addr:item.addr,order:' time desc '};
        table.render({
            elem: '#table_op_log_set_day'
            ,url: "../Api/Log/OpLogDay"
            ,height: '280'
            ,method:'GET'
            ,headers : {'Authorization': 'Bearer '+window.localStorage.getItem("token")}
            ,where: query
            ,page: {
                limit:50,
                limits:[10, 20, 30, 40, 50,100,200,300,400],
                theme: '#3c7cff'
            }
            //,limit:100000
            //,toolbar: '#table_toolbar' //开启头部工具栏，并为其绑定左侧模板
            ,defaultToolbar: ['']
            ,title: ''
            ,even:false
            ,size: 'sm' //小尺寸的表格
            //,skin: 'nob' //无框风格
            ,cols: [[
                {type: 'numbers',title:'序号', fixed: 'left'}
                ,{field:'day', title:'设置日龄',width:110, sort: true}//
                ,{field:'username', title:'操作人',width:110, sort: true}
                ,{field:'time', title:'操作时间',width:160, sort: true}
                ,{field:'res', title:'操作结果', sort: true}

            ]]
        });


        query={sn:item.sn,addr:item.addr,order:' time desc '};
        table.render({
            elem: '#table_op_log_set_calc'
            ,url: "../Api/Log/OpLogCalc"
            ,height: '280'
            ,method:'GET'
            ,headers : {'Authorization': 'Bearer '+window.localStorage.getItem("token")}
            ,where: query
            ,page: {
                limit:50,
                limits:[10, 20, 30, 40, 50,100,200,300,400],
                theme: '#3c7cff'
            }
            //,limit:100000
            //,toolbar: '#table_toolbar' //开启头部工具栏，并为其绑定左侧模板
            ,defaultToolbar: ['']
            ,title: ''
            ,even:false
            ,size: 'sm' //小尺寸的表格
            //,skin: 'nob' //无框风格
            ,cols: [[
                {type: 'numbers',title:'序号', fixed: 'left'}
                ,{field:'calc', title:'校准值',width:110, sort: true}//
                ,{field:'username', title:'操作人',width:110, sort: true}
                ,{field:'time', title:'操作时间',width:160, sort: true}
                ,{field:'res', title:'操作结果', sort: true}

            ]]
        });
    }

    function onViewPlan(item) {
        //console.info(item);
        if(item.model == "fg"){
            content = '../Feed/FgPlanParaReadonly?id='+item.id;
        }else{
            content = '../Feed/FeedPlanParaReadonly?id='+item.id;
        }
        var idx = layer.open({
            area:['95%','85%'],
            type: 2,
            shadeClose: true,
            shade: 0.8,
            title: item.name,
            maxmin: false, //开启最大化最小化按钮
            content: content
        });
    }

    

    function onPig(item){
        var obj = item;
        console.info(obj);
        if(obj.mode==2){
            //显示仔猪
            $(".has_son").show();
        }else{
            $(".has_son").hide();
        }

        layer.open({
            area:['50%','500px'],
            offset: '10%',
            shade: 0.5,
            shadeClose: true,
            type: 1,
            title: '<i class="iconfont icon-pig"></i> '+obj.housename+" "+obj.hnum+" ", //不显示标题
            content: $('#form_pig'), //捕获的元素，注意：最好该指定的元素要存放在body最外层，否则可能被其它的相对元素所影响
            maxmin: false,
            btn: ['保存', '取消'],
            yes: function(index, layero){
                lay_index=index;
                var submit = layero.find("#btn_pig_ok");
                submit.click();
            }
        });

        form.val("form_pig",obj);
        showPigTable(obj);
    }

    //采食历史
    function onFeedHis(item){
        cur_selected_item = item;
        var obj = item;
        console.info(obj);



        layer.open({
            area:['60%','80%'],
            offset: '10%',
            shade: 0.5,
            shadeClose: true,
            type: 1,
            title: '<i class="layui-icon layui-icon-chart"></i> '+obj.housename+" "+obj.hnum+" 采食历史", //不显示标题
            content: $('#form_feed_chart'), //捕获的元素，注意：最好该指定的元素要存放在body最外层，否则可能被其它的相对元素所影响
            maxmin: false,
            btn: [ '关闭']
        });

        var today = moment().format('YYYY-MM-DD'); 
        laydate.render({
            elem: '#id-date'
            ,type: 'date'
            //,range: '~'
            , theme: '#3c7cff'
            ,value: today
            ,isInitValue: true
            ,done: function(value, date, endDate){
                //setTimeout(function(){load();},200);
                console.info(value, date, endDate);
                loadHourRecordChart(obj.addr,item.pig_num,value,obj.sn);
            }
        });

        var active = {
            set: function(othis){
                var THIS = 'layui-bg-normal'
                    ,key = othis.data('key')
                    ,options = {};

                othis.css('background-color', '#3c7cff').siblings().removeAttr('style');
                var val = othis.data('value');
                console.info("value",val);
                day_feed_chart_type = val;
                loadDayHisChart(obj.addr,item.pig_num,obj.sn,obj.mode);
            }
        };
        $('.day_feed_chart_btns .layui-btn').off();
        $('.day_feed_chart_btns .layui-btn').on('click', function(){
            var othis = $(this), type = othis.data('type');
            active[type] ? active[type].call(this, othis) : '';
        });

        loadDayHisChart(obj.addr,item.pig_num,obj.sn,obj.mode);
        loadHourRecordChart(obj.addr,item.pig_num,today,obj.sn);
    }

    //远程下料
    function onManul(item){
        cur_selected_item = item;
        var obj = item;
        
        layer.open({
            //area: 'auto',
            area:['350px','300px'],
            type: 1,
            shade: 0.3,
            offset: '15%',
            shadeClose:true,
           title: '远程控制 '+obj.housename+" "+obj.hnum, 
            content: $('#form_manul'), //捕获的元素，注意：最好该指定的元素要存放在body最外层，否则可能被其它的相对元素所影响
            btn: ['确定', '取消']
            ,yes: function(index, layero){
                lay_index=index;
                var submit = layero.find("#on_btn_manul");
                submit.click();
            }
        });

        //layer.load(1);
        $.ajax({
            type: 'get',
            url: '../Api/Device/Feednode',
            data: {sn:item.sn},
            beforeSend: function(request) {
                request.setRequestHeader("Authorization", 'Bearer '+window.localStorage.getItem("token"));
            },
            dataType: "json",
            success: function (res) {
                if(res.code>=0){
                    list = res.data;
                    console.info(list);
                    if(list.length>0){
                        var para =JSON.parse(list[0].para);
                        console.info(para);
                        if(para.EnWater>0){
                            $(".manul_water").show();
                        }else{
                            $(".manul_water").hide();
                        }
                        form.val("form_manul",{addr:item.addr,tn:item.tn,feed:'0',water:'0'});
                    }
                    resize();
                    
                }else{

                    layer.alert(res.msg);
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                layer.msg('读取设备参数失败');
            },
            complete: function(XMLHttpRequest, textStatus) {
                layer.closeAll('loading');
            },
        });
    }
    //远程下料
    function manul(field){
        console.info(field);
        if(field.feed==0 && field.water==0){
            toastr.warning("请填写有效的数值");
            return;
        }
        var tips="";
        if(field.feed>0){
            tips+=" 下料:"+field.feed+" g";
        }
        if(field.water>0){
            tips+=" 下水:"+field.water+" ml";
        }

        layer.confirm("确认"+tips+"?", function(index){
            layer.close(index);
            layer.load(1);
            $.ajax({
                type: 'PUT',
                url: '../Api/Device/Gw/ManualFeed',
                data: field,
                beforeSend: function(request) {
                    request.setRequestHeader("Authorization", 'Bearer '+window.localStorage.getItem("token"));
                },
                success: function(res){
                    if(res){
                        if(res.code>=0){
                            //保存成功
                            console.info(res.data);
                            var feed_err_arr = [];
                            if(res.data.feed_res==255){
                                feed_err_arr.push("下料超时");
                            }else if(res.data.feed_res==1){
                                feed_err_arr.push("下料失败:动作中");
                            }

                            var water_err_arr = [];
                            if(res.data.water_res==255){
                                water_err_arr.push("下水超时");
                            }else if(res.data.water_res==1){
                                water_err_arr.push("下水失败:动作中");
                            }else if(res.data.water_res==2){
                                water_err_arr.push("下水失败:水阀未开");
                            }

                            if(field.feed>0){
                                if(feed_err_arr.length>0){
                                    toastr.warning(feed_err_arr.join(","));
                                }else{
                                    toastr.success("下料成功");
                                }
                            }
                            
                            if(field.water>0){
                                if(water_err_arr.length>0){
                                    toastr.warning(water_err_arr.join(","));
                                }else{
                                    toastr.success("下水成功");
                                }
                            }
                            
                            
                        }else{
                            //layer.alert(res.msg);
                            toastr.warning(res.msg, "异常");
                        }
                    }
                },
                complete: function(XMLHttpRequest, textStatus) {
                    layer.closeAll('loading');
                },
                dataType: "json"
            });
        
        });
        
    }

    //每日采食曲线
    function loadDayHisChart(addr,pig_num,sn,mode){
        var begin='';
        var end='';
        aweekago = moment().add(-7,"days").format('YYYY-MM-DD');
        amonthago = moment().add(-30,"days").format('YYYY-MM-DD');
        if(day_feed_chart_type){
            if(day_feed_chart_type=="day_feed_chart_7day"){
                begin = aweekago;
            }else if(day_feed_chart_type=="day_feed_chart_30day"){
                begin = amonthago;
            }
        }else{
            begin = aweekago;
        }

        var obj={addr:addr,sn:sn,begin:begin,end:end,order:" his_date asc "};
        if(!day_his_chart){
            day_his_chart = echarts.init(document.getElementById('day_his_chart'));
        }
        day_his_chart.showLoading({maskColor: 'rgba(0, 0, 0, 0.2)',textColor: '#fff',text: 'loading',});
        $.ajax({
            type: 'GET',
            url: '../Api/History/StatusHis',
            data: obj,
            beforeSend: function(request) {
                request.setRequestHeader("Authorization", 'Bearer '+window.localStorage.getItem("token"));
            },
            dataType: "json",
            success: function (res) {
                if(res.code>=0){

                    var day_arr =[];
                    var val_arr =[];
                    var low_arr =[];
                    var standard_arr =[];

                    var max = 0;

                    //console.info(res.data)
                    for(var i=0;i<res.data.length;i++){
                        var his = res.data[i];
                        
                        /*var feed = parseFloat(his.day_use_feed_auto)+parseFloat(his.day_use_feed_man);
                        var max_feed = parseFloat(his.max_feed);

                        if(max<feed){
                            max = feed;
                        }
                        if(max < max_feed){
                            max = max_feed;
                        }

                        val_arr.push(parseFloat(feed.toFixed(2)));
                        val1_arr.push(max_feed);
                        day_arr.push(moment(his.his_date).format("MM/DD") );
                        */

                        var avg_day_use_feed = his.avg_day_use_feed;
                        val_arr.push(parseFloat(avg_day_use_feed.toFixed(2)));

                        var low_standard = his.low_standard;
                        low_arr.push(parseFloat(low_standard.toFixed(2)));

                        if(mode==1||mode==2){
                            standard_arr.push(null);
                        }else{
                            var standard = his.standard;
                            standard_arr.push(parseFloat(standard.toFixed(2)));
                        }
                        
                        

                        day_arr.push(moment(his.his_date).format("MM/DD") );
                    }


                    day_his_chart_options.series[0].data= val_arr;
                    day_his_chart_options.series[1].data= low_arr;
                    day_his_chart_options.series[2].data= standard_arr;
                    day_his_chart_options.xAxis[0].data = day_arr;

                    setTimeout(function(){
                        day_his_chart.setOption(day_his_chart_options);
                        day_his_chart.resize();
                    },200);
                }else{
                    layer.alert(res.msg);
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                layer.msg('加载信息失败');
            },
            complete: function(XMLHttpRequest, textStatus) {
                day_his_chart.hideLoading();
            },

        });
    }

    //导出日采食曲线
    function onExportDayFeed(){
        var begin='';
        var end='';
        aweekago = moment().add(-7,"days").format('YYYY-MM-DD');
        amonthago = moment().add(-30,"days").format('YYYY-MM-DD');
        if(day_feed_chart_type){
            if(day_feed_chart_type=="day_feed_chart_7day"){
                begin = aweekago;
            }else if(day_feed_chart_type=="day_feed_chart_30day"){
                begin = amonthago;
            }
        }else{
            begin = aweekago;
        }
        var end = moment().add(1,"days").format('YYYY-MM-DD');

        var obj={sn:cur_selected_item.sn,begin:begin,end:end,order:" his_date asc "};
        
        layer.load(1);
        var url="../Api/History/FeedHis/Export?"+encodeUrl(obj);
        console.info(url);

        var xhh = new XMLHttpRequest();
        xhh.open("get", url );
        xhh.setRequestHeader("Authorization", token);
        xhh.setRequestHeader("Content-Type","application/json");
        xhh.responseType = 'blob';
        xhh.onload = function () {
            layer.closeAll('loading');
            // 请求完成
            if (this.status === 200) {
                // 返回200
                var blob = this.response;
                var reader = new FileReader();
                reader.readAsDataURL(blob);    // 转换为base64，可以直接放入a表情href
                reader.onload = function (e) {
                    // 转换完成，创建一个a标签用于下载
                    var a = document.createElement('a');
                    a.download = cur_selected_item.housename+"_" +cur_selected_item.hnum+ " 日采食记录.xlsx";
                    a.href = e.target.result;
                    $("body").append(a);    // 修复firefox中无法触发click
                    a.click();
                    $(a).remove();
                }
            }else{
                console.debug(this);
            }
        };
        xhh.send();
    }

    //小时采食曲线
    function loadHourRecordChart(addr,pig_num,date,sn){
        var begin=date;
        var end=moment(date).add(1,"days").format('YYYY-MM-DD');
        var obj={sn:sn,addr:addr,begin:begin,end:end,order:" rectime asc ",begin_end:0,tb_record:0};
        if(!hour_his_chart){
            hour_his_chart = echarts.init(document.getElementById('hour_his_chart'));
        }
        hour_his_chart.showLoading({maskColor: 'rgba(0, 0, 0, 0.2)',textColor: '#fff',text: 'loading',});
        $.ajax({
            type: 'GET',
            url: '../Api/History/FeedRecord',
            data: obj,
            beforeSend: function(request) {
                request.setRequestHeader("Authorization", 'Bearer '+window.localStorage.getItem("token"));
            },
            dataType: "json",
            success: function (res) {
                if(res.code>=0){

                    var today = moment().format('YYYY-MM-DD'); 

                    var hour_arr =[];
                    var hour_desc_arr =[];
                    var feed_arr =[];
                    var water_arr =[];
                    var avg_feed_arr =[];
                    for(var i=0;i<24;i++){
                        var hour = i;
                        hour_arr.push(hour);
                        var start = moment(today).add(hour,"hours").format('HH:00');
                        var finish = moment(today).add(hour+1,"hours").format('HH:00');
                        hour_desc_arr.push(start+"-"+finish);

                        var sum_feed = 0;
                        var sum_water = 0;
                        var avg_feed = 0;

                        //增减判断res.data是null的情况
                        if(res.data==null){
                            feed_arr.push(0);
                            water_arr.push(0);
                            avg_feed_arr.push(0);
                            continue;
                        }

                        for(var x=0;x<res.data.length;x++){
                            var his = res.data[x];
                            var feed_type = his.feed_type;
                            var amount = parseFloat(his.amount);
                            var date = his.rectime;
                            if(moment(date).hour()==hour){
                                if(feed_type>0)
                                {
                                    //料
                                    sum_feed+=amount;
                                }
                                else
                                {
                                    sum_water+=amount;
                                }
                            }
                        }

                        

                        feed_arr.push(sum_feed.toFixed(2));
                        water_arr.push(sum_water.toFixed(2));
                        if(pig_num>0)
                        {
                            avg_feed_arr.push((sum_feed/pig_num).toFixed(2));
                        }
                        else
                        {
                            avg_feed_arr.push(0);
                        }
                    }

                    console.info("feed_arr",feed_arr);
                    console.info("water_arr",water_arr);
                    console.info("hour_arr",hour_arr);
                    console.info("hour_desc_arr",hour_desc_arr);


                    hour_his_chart_options.series[0].data= feed_arr;
                    hour_his_chart_options.series[1].data= water_arr;
                    hour_his_chart_options.series[2].data= avg_feed_arr;

                    hour_his_chart_options.xAxis[0].data = hour_desc_arr;
                    

                    setTimeout(function(){
                        hour_his_chart.setOption(hour_his_chart_options);
                        hour_his_chart.resize();
                    },200);
                }else{
                    layer.alert(res.msg);
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                layer.msg('加载信息失败');
            },
            complete: function(XMLHttpRequest, textStatus) {
                hour_his_chart.hideLoading();
            },

        });
    }

    //导出小时采食曲线
    function onExportHourFeed(){
        console.info("cur_selected_item",cur_selected_item);
        var date = $("#id-date").html();
        console.info("date",date);

        var begin=date;
        var end=moment(date).add(1,"days").format('YYYY-MM-DD');
        var obj={sn:cur_selected_item.sn,begin:begin,end:end};
        
        layer.load(1);
        var url="../Api/History/FeedHis/ExportHourFeed?"+encodeUrl(obj);
        console.info(url);

        var xhh = new XMLHttpRequest();
        xhh.open("get", url );
        xhh.setRequestHeader("Authorization", token);
        xhh.setRequestHeader("Content-Type","application/json");
        xhh.responseType = 'blob';
        xhh.onload = function () {
            layer.closeAll('loading');
            // 请求完成
            if (this.status === 200) {
                // 返回200
                var blob = this.response;
                var reader = new FileReader();
                reader.readAsDataURL(blob);    // 转换为base64，可以直接放入a表情href
                reader.onload = function (e) {
                    // 转换完成，创建一个a标签用于下载
                    var a = document.createElement('a');
                    a.download = cur_selected_item.housename+"_" +cur_selected_item.hnum+ " 小时采食曲线记录.xlsx";
                    a.href = e.target.result;
                    $("body").append(a);    // 修复firefox中无法触发click
                    a.click();
                    $(a).remove();
                }
            }else{
                console.debug(this);
            }
        };
        xhh.send();
    }

    //饲喂方案
    function onFeedPlan(item){
        var obj={};
        obj.device_addr = item.addr;
        obj.housename = item.housename;
        obj.device_type = item.device_type;
        obj.hnum = item.hnum;
        obj.sn = item.sn;
        if(item.online){
            //在线
        }
        else{
            //离线
        }
        if(item.model == "fg"){
            content = '../Device/ParaFgReadonly?'+$.param(obj);
        }else{
            content = '../Device/ParaReadonly?'+$.param(obj);
        }
        var idx = layer.open({
            area:['95%','85%'],
            type: 2,
            shadeClose: true,
            shade: 0.8,
            title: item.farmname+" "+item.housename+" "+item.hnum +" 饲喂方案",
            maxmin: false, //开启最大化最小化按钮
            content: content
        });
    }

    //参数操作历史
    function onParaOpHisReadonly(item){
        var idx = layer.open({
            area:['95%','85%'],
            type: 2,
            shadeClose: true,
            shade: 0.8,
            title: item.farmname+" "+item.housename+" "+item.feed_plan_name,
            maxmin: false, //开启最大化最小化按钮
            content: '../Device/ParaOpHisReadonly?'+$.param(item)
        });
    }

    var timeoutID=0;
    function onPlanFilter(e){
        console.info(e.value);
        clearTimeout(timeoutID); //两次输入时间小于500ms时 清除上一个延时器
        //设置新的延时器
        timeoutID = setTimeout(function(){  
           //ajax请求
            Table1.reload({
                where: {key:e.value}
            });
        },500);
        
    }

    function searchPlan(params) {
        Table1.reload({
            where: params
            ,page: {
                curr: 1 //重新从第 1 页开始
            }
        });
    }

    function onPigItemAdd(){
        var item = form.val("form_pig");
        var obj={
            id:'',
            addr:item.addr,
            sn:item.sn,
            earmark:'',
            pig_type:'',
            weight:'',
        };
        console.info(obj)
        form.val("form_pig_item",obj);
        layer.open({
            //area: 'auto',
            area:['400px','350px'],
            type: 1,
            shade: 0.3,
            offset: '15%',
            shadeClose:true,
            title: '新增猪', //不显示标题
            content: $('#form_pig_item'), //捕获的元素，注意：最好该指定的元素要存放在body最外层，否则可能被其它的相对元素所影响
            btn: ['确定', '取消']
            ,yes: function(index, layero){
                lay_index=index;
                var submit = layero.find("#btn_pig_item_ok");
                submit.click();
            }
        });
    }
    function onPigItemEdit(item){
        console.info("onPigItemEdit",item)
        var obj={
            id:item.id,
            addr:item.addr,
            sn:item.sn,
            earmark:item.earmark,
            pig_type:item.pig_type,
            weight:item.weight,
        };
        console.info(obj)
        form.val("form_pig_item",obj);
        layer.open({
            //area: 'auto',
            area:['400px','350px'],
            type: 1,
            shade: 0.3,
            offset: '15%',
            shadeClose:true,
            title: '修改猪', //不显示标题
            content: $('#form_pig_item'), //捕获的元素，注意：最好该指定的元素要存放在body最外层，否则可能被其它的相对元素所影响
            btn: ['确定', '取消']
            ,yes: function(index, layero){
                lay_index=index;
                var submit = layero.find("#btn_pig_item_ok");
                submit.click();
            }
        });
    }

    function onPigItemDelete(item){
        console.info("onPigItemDelete",item)
        layer.confirm('确定删除'+item.earmark+'?', function(index){
            layer.close(index); //再执行关闭
            layer.load(1);
            $.ajax({
                type: 'DELETE',
                url: '../Api/Pig',
                data: {id:item.id},
                beforeSend: function(request) {
                    request.setRequestHeader("Authorization", 'Bearer '+window.localStorage.getItem("token"));
                },
                dataType: "json",
                success: function (res) {
                    if(res.code>=0){
                        toastr.success(res.msg);
                        showPigTable(item);
                    }else{
                        toastr.warning(res.msg, "异常");
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    layer.msg('加载信息失败');
                },
                complete: function(XMLHttpRequest, textStatus) {
                    layer.closeAll('loading');
                },

            });
        });
    }

    function savePigItem(field){
        console.info(field);
        var type="POST";
        if(field.id.length>0){
            type="PUT";
        }
        layer.load(1);
        $.ajax({
            type: type,
            url: '../Api/Pig',
            data: field,
            beforeSend: function(request) {
                request.setRequestHeader("Authorization", 'Bearer '+window.localStorage.getItem("token"));
            },
            dataType: "json",
            success: function (res) {
                if(res.code>=0){
                    layer.close(lay_index);
                    toastr.success("保存成功");
                    showPigTable(field);
                }else{
                    toastr.warning(res.msg, "异常");
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                layer.msg('加载信息失败');
            },
            complete: function(XMLHttpRequest, textStatus) {
                layer.closeAll('loading');
            },

        });
    }

    function savePig(field){
        console.info(field);
        layer.load(1);
        $.ajax({
            type: "PUT",
            url: '../Api/Pig/PigNum',
            data: field,
            beforeSend: function(request) {
                request.setRequestHeader("Authorization", 'Bearer '+window.localStorage.getItem("token"));
            },
            dataType: "json",
            success: function (res) {
                if(res.code>=0){
                    layer.close(lay_index);
                    toastr.success("保存成功");
                    search();
                }else{
                    toastr.warning(res.msg, "异常");
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                layer.msg('加载信息失败');
            },
            complete: function(XMLHttpRequest, textStatus) {
                layer.closeAll('loading');
            },

        });
    }

    function treeOnClick(event, treeId, treeNode) {
        selectedTreeNode=treeNode;
        console.info(selectedTreeNode);
        if(selectedTreeNode.type=="root"){
            toastr.info("请选择栏舍节点查看饲喂器列表");
        }
        else if(selectedTreeNode.type=="farm"){
            toastr.info("请选择栏舍节点查看饲喂器列表");
        }else if(selectedTreeNode.type=="house"){
            
            //先获取栏舍信息，再展示
            getHouseSummaryInfo(selectedTreeNode.houseid).then(function(res) {
                if(res && res.code>=0){
                    var list = res.data;
                    if (list && list.length > 0) {
                        var item = list[0];
                        pig_num_total = item.pig_num_total | 0;
                        
                    }else{
                        pig_num_total =  0;
                    }
                    loadNodesTable();
                }else{
                    layer.alert(res.msg);
                }
            });

            renderSelect(selectedTreeNode.id);

            getHouse(selectedTreeNode.houseid).then(function(res) {
                if(res && res.code>=0){
                    var list = res.data;
                    console.info(list);
                    if(list.length>0){
                        var item = list[0];
                        house_type = item.house_type;
                        housename = item.housename;
                        farmname = item.farmname;
                        group_name = item.group_name;
                        area_name = item.area_name;
                        console.info(item);
                        var temp = item.dfxw_unit_avg_temperature;
                        if(temp){
                            if(-127!=temp){
                                $("#id-temp").html(temp+" ℃") ;
                            }
                            else{
                                $("#id-temp").html("N/A") ;
                            }
                        }else{
                            $("#id-temp").html("N/A") ;
                        }

                        dfxw_unit_day_age = item.dfxw_unit_day_age;
                        dfxw_unit_num = item.dfxw_unit_num;
                        linkage_feed = item.linkage_feed;
                        dfxw_id = item.dfxw_id;

                        if(dfxw_unit_num){
                            if(-127!=dfxw_unit_num){
                                $("#id-mespig").html(dfxw_unit_num) ;
                            }
                            else{
                                $("#id-mespig").html("N/A") ;
                            }
                        }else{
                            $("#id-mespig").html("N/A") ;
                        }

                        if(dfxw_unit_day_age){
                            if(-127!=dfxw_unit_day_age){
                                $("#id-mesday").html(dfxw_unit_day_age) ;
                            }
                            else{
                                $("#id-mesday").html("N/A") ;
                            }
                        }else{
                            $("#id-mesday").html("N/A") ;
                        }
                    }
                }else{
                    layer.alert(res.msg);
                }
            });

            

        }else if(selectedTreeNode.type=="hnum"){
            loadNodesTable();
            renderSelect(selectedTreeNode.id);
        }
        else{

        }
    }


    function renderSelect(){
        var obj={};
        if(selectedTreeNode.type=="house"){
            obj={houseid:selectedTreeNode.id};
        }else if(selectedTreeNode.type=="farm"){
            obj={farmid:selectedTreeNode.id};
        }else if(selectedTreeNode.type=="hnum"){
            obj={houseid:selectedTreeNode.houseid,hnum_prefix:selectedTreeNode.hnum_prefix};
        }
        $.ajax({
            type: 'GET',
            url: '../Api/Utils/Hnum',
            data: obj,
            beforeSend: function(request) {
                request.setRequestHeader("Authorization", 'Bearer '+window.localStorage.getItem("token"));
            },
            dataType: "json",
            success: function (res) {
                console.info(res)
                if(res.code>=0){
                    var items = res.data;
                    console.info(items)
                    //栏舍下拉
                    var html="<option value='' ></option>";
                    for(var i=0;i<items.length;i++){
                        var selectd="";
                        html+="<option "+selectd+" value=\""+items[i].hnum+"\">"+items[i].hnum+"</option>";
                    }
                    $("select[name='hnum']").html(html);
                    form.render('select');
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                layer.msg('加载设备类型失败');
            }
        });


        var html="<option value='' ></option>";
        for(var i=0;i<SYS_PIG_TYPE.length;i++){
            var selectd="";
            html+="<option "+selectd+" value=\""+SYS_PIG_TYPE[i].data_value+"\">"+SYS_PIG_TYPE[i].data_text+"</option>";
        }
        $("select[name='pig_type']").html(html);
        form.render('select');

    }

    function renderGroupSelect(){
        $.ajax({
            type: 'GET',
            url: '../Api/Group',
            data: {},
            beforeSend: function(request) {
                request.setRequestHeader("Authorization", 'Bearer '+window.localStorage.getItem("token"));
            },
            dataType: "json",
            success: function (res) {
                console.info(res)
                if(res.code>=0){
                    var items = res.data;
                    console.info(items)
                    //栏舍下拉
                    var html="<option value='' >请选择集团</option>";
                    for(var i=0;i<items.length;i++){
                        var selectd="";
                        html+="<option "+selectd+" value=\""+items[i].group_code+"\">"+items[i].group_name+"</option>";
                    }
                    $("select[name='group_code']").html(html);
                    form.render('select');
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                layer.msg('加载集团失败');
            }
        });
    }

    function renderFarmSelect(group_code){
        $.ajax({
            type: 'GET',
            url: '../Api/Farm/List',
            data: {},
            beforeSend: function(request) {
                request.setRequestHeader("Authorization", 'Bearer '+window.localStorage.getItem("token"));
            },
            dataType: "json",
            success: function (res) {
                console.info(res)
                if(res.code>=0){
                    var items = res.data;
                    console.info(items)
                    //栏舍下拉
                    var html="<option value='' >请选择场区</option>";
                    for(var i=0;i<items.length;i++){
                        var selectd="";
                        if(group_code){
                            if(items[i].group_code==group_code){
                                html+="<option "+selectd+" value=\""+items[i].id+"\">"+items[i].farmname+"</option>";
                            }
                        }
                        else{
                            html+="<option "+selectd+" value=\""+items[i].id+"\">"+items[i].farmname+"</option>";
                        }
                        
                        
                    }
                    $("select[name='farmid']").html(html);
                    form.render('select');
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                layer.msg('加载集团失败');
            }
        });
    }

    function search(params) {
        //loadNodesTable();
        //selectedTreeNode.click();
        if(selectedTreeNode){
            $("#"+selectedTreeNode.tId+"_a").click();
        }
        
    }

    function getFont(treeId, node) {
        return node.font ? node.font : {};
    }

    function loadTree() {
        console.info("loadTree")
        /*layer.load(1);
        $.ajax({
            type: 'GET',
            url: '../Api/Topo/GetAsync',
            data: {show_hnum:1,device_type:'DMXFGW',root:1},
            beforeSend: function(request) {
                request.setRequestHeader("Authorization", 'Bearer '+window.localStorage.getItem("token"));
            },
            dataType: "json",
            success: function (data) {
                //var data=data.data;
                var nodes=setDataIcon(data.data);
                console.info(nodes);
                zTree = $.fn.zTree.init($("#treeDemo"), tree_setting, nodes);
                var nodes = zTree.getNodesByParam("type", "farm", null);
                if(nodes.length>0){
                    const node = nodes[0];
                    console.info(node);
                    zTree.selectNode(node);
                    setTimeout(function(){zTree.setting.callback.onClick(null,null,node);},500);
                }

            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                layer.msg('加载信息失败');
            },
            complete: function(XMLHttpRequest, textStatus) {
                layer.closeAll('loading');
            },
        });
        */

        zTree = $.fn.zTree.init($("#treeDemo"), tree_setting);

    }

    //设置图标
    function setDataIcon(data){

        for(let i=0; i<data.length; i++){
            var node=data[i];

            node['font']={'color':'#333'};
            if(node.type=='group'){
                //node.name = "";
                node["icon"]="../plugins/zTree/css/metroStyle/img/net.png";
                //node.isParent=true;
                node.open = true;
            }
            else if(node.type=='area'){
                node["icon"]="../plugins/zTree/css/metroStyle/img/area.png";
                //node.isParent=true;
                node.open = true;
            }
            else if(node.type=='farm'){
                node["icon"]="../plugins/zTree/css/metroStyle/img/location.png";
                node.isParent=true;
            }else if(node.type=='house'){
                node["icon"]="../plugins/zTree/css/metroStyle/img/house.png";
                node.isParent=false;
                if(node.device_online)
                {
                    node['font']={'color':'#3c7cff'};
                }else{
                    node['font']={'color':'#A3A8B6'};
                }
                //node['font']={'color':'#3c7cff','font-weight':"bold"};
            }
            else if(node.type=='HZFGW'||node.type=='DMXFGW') {
                node["icon"] = "../plugins/zTree/css/metroStyle/img/gw.png";
                node.isParent=true;
                node.open=true;
            }
            else if(node.type=='hnum') {
                node["icon"] = "../plugins/zTree/css/metroStyle/img/farm.png";
                //node.isParent=true;
                //node.open=true;
            }
            else if(node.type=='feed'){
                if(node.enable>0){
                    if(node.online>0){
                        node["icon"]="../plugins/zTree/css/metroStyle/img/node.png";
                        node['font']={'color':'#3c7cff'};
                        if(node.alarm>0){
                            node["icon"]="../plugins/zTree/css/metroStyle/img/node.png";
                            node['font']={'color':'#f29114'};
                        }
                    }else if(node.online==0){
                        node["icon"]="../plugins/zTree/css/metroStyle/img/node_offline.png";
                        node['font']={'color':'#333'};
                    }else if(node.online==-1){
                        node["icon"]="../plugins/zTree/css/metroStyle/img/node.png";
                        node['font']={'color':'#fff'};
                    }
                }else{
                    node["icon"]="../plugins/zTree/css/metroStyle/img/no.png";
                    node['font']={'color':'#333'};
                }

                node.isParent=false;
            }
            if(node['children']){
                var data1=node.children;
                setDataIcon(data1);
            }
        }
        return data;
    }

    $(window).resize(function () {
        //console.info('resize')
        resize();
    });
    function resize() {

        if (day_his_chart) {
            day_his_chart.resize();
        }
        if(hour_his_chart){
            hour_his_chart.resize();
        }

        var h = $('#wd_param').height();
        $("#tree1").slimScroll({
            height: h-25,
            size: '4px', //组件宽度
            color: '#eee', //滚动条颜色
            position: 'right', //组件位置：left/right
            distance: '0px', //组件与侧边之间的距离
            start: 'top', //默认滚动位置：top/bottom
            opacity: .4, //滚动条透明度
            alwaysVisible: true, //是否 始终显示组件
            disableFadeOut: false, //是否 鼠标经过可滚动区域时显示组件，离开时隐藏组件
            railVisible: true, //是否 显示轨道
            railColor: '#333', //轨道颜色
            railOpacity: .2, //轨道透明度
            railDraggable: true, //是否 滚动条可拖动
            railClass: 'slimScrollRail', //轨道div类名
            barClass: 'slimScrollBar', //滚动条div类名
            wrapperClass: 'slimScrollDiv', //外包div类名
            allowPageScroll: true, //是否 使用滚轮到达顶端/底端时，滚动窗口
            wheelStep: 10, //滚轮滚动量
            touchScrollStep: 200, //滚动量当用户使用手势
            borderRadius: '7px', //滚动条圆角
            railBorderRadius: '7px' //轨道圆角
        });

        $(".content-scroll").slimScroll({
            height: h-90,
            size: '4px', //组件宽度
            color: '#eee', //滚动条颜色
            position: 'right', //组件位置：left/right
            distance: '0px', //组件与侧边之间的距离
            start: 'top', //默认滚动位置：top/bottom
            opacity: .4, //滚动条透明度
            alwaysVisible: true, //是否 始终显示组件
            disableFadeOut: false, //是否 鼠标经过可滚动区域时显示组件，离开时隐藏组件
            railVisible: true, //是否 显示轨道
            railColor: '#333', //轨道颜色
            railOpacity: .2, //轨道透明度
            railDraggable: true, //是否 滚动条可拖动
            railClass: 'slimScrollRail', //轨道div类名
            barClass: 'slimScrollBar', //滚动条div类名
            wrapperClass: 'slimScrollDiv', //外包div类名
            allowPageScroll: true, //是否 使用滚轮到达顶端/底端时，滚动窗口
            wheelStep: 10, //滚轮滚动量
            touchScrollStep: 200, //滚动量当用户使用手势
            borderRadius: '7px', //滚动条圆角
            railBorderRadius: '7px' //轨道圆角
        });

        var h = $('#form_status').height();

        $("#tree2").slimScroll({
            height: h-25,
            size: '4px', //组件宽度
            color: '#eee', //滚动条颜色
            position: 'right', //组件位置：left/right
            distance: '0px', //组件与侧边之间的距离
            start: 'top', //默认滚动位置：top/bottom
            opacity: .4, //滚动条透明度
            alwaysVisible: true, //是否 始终显示组件
            disableFadeOut: false, //是否 鼠标经过可滚动区域时显示组件，离开时隐藏组件
            railVisible: true, //是否 显示轨道
            railColor: '#333', //轨道颜色
            railOpacity: .2, //轨道透明度
            railDraggable: true, //是否 滚动条可拖动
            railClass: 'slimScrollRail', //轨道div类名
            barClass: 'slimScrollBar', //滚动条div类名
            wrapperClass: 'slimScrollDiv', //外包div类名
            allowPageScroll: true, //是否 使用滚轮到达顶端/底端时，滚动窗口
            wheelStep: 10, //滚轮滚动量
            touchScrollStep: 200, //滚动量当用户使用手势
            borderRadius: '7px', //滚动条圆角
            railBorderRadius: '7px' //轨道圆角
        });
        $(".content-scroll1").slimScroll({
            height: h-50,
            size: '4px', //组件宽度
            color: '#eee', //滚动条颜色
            position: 'right', //组件位置：left/right
            distance: '0px', //组件与侧边之间的距离
            start: 'top', //默认滚动位置：top/bottom
            opacity: .4, //滚动条透明度
            alwaysVisible: true, //是否 始终显示组件
            disableFadeOut: false, //是否 鼠标经过可滚动区域时显示组件，离开时隐藏组件
            railVisible: true, //是否 显示轨道
            railColor: '#333', //轨道颜色
            railOpacity: .2, //轨道透明度
            railDraggable: true, //是否 滚动条可拖动
            railClass: 'slimScrollRail', //轨道div类名
            barClass: 'slimScrollBar', //滚动条div类名
            wrapperClass: 'slimScrollDiv', //外包div类名
            allowPageScroll: true, //是否 使用滚轮到达顶端/底端时，滚动窗口
            wheelStep: 10, //滚轮滚动量
            touchScrollStep: 200, //滚动量当用户使用手势
            borderRadius: '7px', //滚动条圆角
            railBorderRadius: '7px' //轨道圆角
        });

        $(".detail-tab-scroll").slimScroll({
            height: '320',
            size: '4px', //组件宽度
            color: '#eee', //滚动条颜色
            position: 'right', //组件位置：left/right
            distance: '0px', //组件与侧边之间的距离
            start: 'top', //默认滚动位置：top/bottom
            opacity: .4, //滚动条透明度
            alwaysVisible: true, //是否 始终显示组件
            disableFadeOut: false, //是否 鼠标经过可滚动区域时显示组件，离开时隐藏组件
            railVisible: true, //是否 显示轨道
            railColor: '#333', //轨道颜色
            railOpacity: .2, //轨道透明度
            railDraggable: true, //是否 滚动条可拖动
            railClass: 'slimScrollRail', //轨道div类名
            barClass: 'slimScrollBar', //滚动条div类名
            wrapperClass: 'slimScrollDiv', //外包div类名
            allowPageScroll: true, //是否 使用滚轮到达顶端/底端时，滚动窗口
            wheelStep: 10, //滚轮滚动量
            touchScrollStep: 200, //滚动量当用户使用手势
            borderRadius: '7px', //滚动条圆角
            railBorderRadius: '7px' //轨道圆角
        });

        $(".tree-div").slimScroll({
            height: $(window).height()-10,
            size: '4px', //组件宽度
            color: '#eee', //滚动条颜色
            position: 'right', //组件位置：left/right
            distance: '0px', //组件与侧边之间的距离
            start: 'top', //默认滚动位置：top/bottom
            opacity: .4, //滚动条透明度
            alwaysVisible: true, //是否 始终显示组件
            disableFadeOut: false, //是否 鼠标经过可滚动区域时显示组件，离开时隐藏组件
            railVisible: true, //是否 显示轨道
            railColor: '#333', //轨道颜色
            railOpacity: .2, //轨道透明度
            railDraggable: true, //是否 滚动条可拖动
            railClass: 'slimScrollRail', //轨道div类名
            barClass: 'slimScrollBar', //滚动条div类名
            wrapperClass: 'slimScrollDiv', //外包div类名
            allowPageScroll: true, //是否 使用滚轮到达顶端/底端时，滚动窗口
            wheelStep: 10, //滚轮滚动量
            touchScrollStep: 200, //滚动量当用户使用手势
            borderRadius: '7px', //滚动条圆角
            railBorderRadius: '7px' //轨道圆角
        });

        //$('.tree-div').height($(window).height()-60);
    }

    function beautyTimeSpan(seconds){
        var str ="";
        var day_val=parseInt(seconds/(60*60*24)) ;
        var rest=seconds % (60*60*24);
        var hour_val= parseInt(rest/(60*60));
        rest=seconds % (60*60);
        var minite_val= parseInt(rest/(60));
        rest=seconds % (60);

        if(day_val>0){
            str+=(day_val + "天")
        }
        if(hour_val>0){
            str+=(hour_val + "时")
        }
        if(minite_val>0){
            str+=(minite_val + "分")
        }
        if(rest>0){
            str+=(rest + "秒")
        }

        return str
    }

    function formatminutes(date){
        $($(".laydate-time-list li ol")[2]).find("li").remove(); //清空秒
    }
    function encodeUrl(obj) {
        var str = [];
        for (var p in obj)
            if (obj.hasOwnProperty(p)) {
                str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
            }
        return str.join("&");
    }

    //去除多余小数点和0
    function removeExtraDotAndZero(num) {
        // 将数字转换为字符串
        let str = num.toString();
        // 使用正则表达式去除多余的小数点和末尾的0
        str = str.replace(/[.]/, ""); // 先移除小数点前的多余0
        str = str.replace(/[.]/, "."); // 然后确保只有一个小数点
        str = str.replace(/[0]+$/, ""); // 移除末尾的0
        str = str.replace(/[\.]0+$/, ""); // 移除末尾的小数点和0
        str = str.replace(/^[-]0*/, "-"); // 移除开头的0，但保留负号
        // 将处理后的字符串转换回数字
        return Number(str);
    }

    function removeStrExtraDotAndZero(str) {
        // 使用正则表达式去除多余的小数点和末尾的0
        str = str.replace(/[.]/, ""); // 先移除小数点前的多余0
        str = str.replace(/[.]/, "."); // 然后确保只有一个小数点
        str = str.replace(/[0]+$/, ""); // 移除末尾的0
        str = str.replace(/[\.]0+$/, ""); // 移除末尾的小数点和0
        str = str.replace(/^[-]0*/, "-"); // 移除开头的0，但保留负号
        // 将处理后的字符串转换回数字
        return (str);
    }

    // 示例
    /*console.log(removeExtraDotAndZero(10.000)); // 输出 10
    console.log(removeExtraDotAndZero(10.100)); // 输出 10.1
    console.log(removeExtraDotAndZero(10.10));  // 输出 10.1
    console.log(removeExtraDotAndZero(0.100));  // 输出 0.1
    console.log(removeExtraDotAndZero(0.00));   // 输出 0
    */
</script>
<script src="../js/check_screen.js?v=${.Config.basic.version}"></script>
</body>

<style>
    .hover-btn:focus, .hover-btn:hover {
        text-decoration: none;
        cursor: pointer;
        filter: alpha(opacity=50);
        opacity: .5;
    }

    .layui-btn-sm {
        height: 20px;
        line-height: 20px;
        padding: 0 5px;
        font-size: 12px;
    }

</style>

<form class="layui-form" lay-filter="form_plan" id="form_plan" style="padding: 10px;display:none;">
    <div class="layui-form-item">
        <div class="layui-input-inline" style="width: 150px;">
            <select name="group_code" lay-filter="group_code" lay-verify="" lay-search="" placeholder="请选择集团">
                <option value="">请选择集团</option>
            </select>
        </div>
        <div class="layui-input-inline" style="width: 150px;">
            <select name="farmid" lay-filter="farmid"  lay-verify="" lay-search="" placeholder="请选择场区">
                <option value="">请选择场区</option>
            </select>
        </div>
        <!-- <div class="layui-inline">
            <div class="layui-input-inline">
                <input type="text" oninput="onPlanFilter(this);" id="plan_key" placeholder="请输入关键字过滤" lay-verify="" autocomplete="off" class="layui-input">
            </div>
        </div> -->
        <div class="layui-inline">
            <div class="layui-input-inline">
                <input type="text" id="plan_key" name="key" placeholder="关键字" lay-verify="" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-inline">
            <button type="submit" class="layui-btn layui-btn-sm layui-btn-normal" lay-submit="" lay-filter="btn_search_plan"><i class="layui-icon layui-icon-search"></i>查询</button>
            <!--<button type="button" class="layui-btn layui-btn-normal layui-btn-sm action-export layui-hide" lay-submit="" lay-filter="btn_search"><i class="fa fa-file-excel-o"></i> 导出</button>-->
        </div>
    </div>
    
    <table class="layui-hide" id="table_plan" lay-filter="table_plan"></table>
</form>

<form class="layui-form" lay-filter="form_pig" id="form_pig" style="padding: 10px;display:none;">
    <div class="layui-form-item layui-hide">
        <input type="text" name="id" lay-verify="" placeholder="" autocomplete="off" class="layui-input" style="width: 100%">
        <input type="text" name="addr" lay-verify="" placeholder="" autocomplete="off" class="layui-input" style="width: 100%">
        <input type="text" name="sn" lay-verify="" placeholder="" autocomplete="off" class="layui-input" style="width: 100%">
        <input type="text" name="mode" lay-verify="" placeholder="" autocomplete="off" class="layui-input" style="width: 100%">
    </div>
    <!-- <div class="toolbar" style="height: 20px;">
        
    </div> -->
    <blockquote class="layui-elem-quote" style="font-size: 0.7rem;">
        猪数量维护
    </blockquote>
    <div class="layui-form-item">
        <label class="layui-form-label"><span class="layui-text-red">*</span> 栏位猪只</label>
        <div class="layui-input-inline">
            <input type="text" name="pig_num" id="pig_num" lay-verify="number" maxlength="2" value="0" lay-verType="tips" placeholder="" autocomplete="off" class="layui-input" >
        </div>
        <label class="layui-form-label">头</label>
    </div>

    <div class="layui-form-item has_son">
        <label class="layui-form-label"><span class="layui-text-red">*</span> 仔猪</label>
        <div class="layui-input-inline">
            <input type="text" name="son" id="son" lay-verify="number" maxlength="2" value="0" lay-verType="tips" placeholder="" autocomplete="off" class="layui-input" >
        </div>
        <label class="layui-form-label">头</label>
    </div>

    <blockquote class="layui-elem-quote" style="font-size: 0.7rem;">
        猪档案维护
        <i class="fr layui-icon layui-text-black layui-icon-add-circle hand hover-btn" onclick="onPigItemAdd();"></i>
    </blockquote>

    <!-- <blockquote class="layui-elem-quote" id="id-title">
        <span><i class="iconfont icon-pig"></i><span id="pig_num"> 无猪只 </span></span>
        <i class="fr layui-icon layui-text-black layui-icon-add-circle hand hover-btn"></i>
    </blockquote> -->
    <table class="layui-hide" id="table_pig" lay-filter="table_pig"></table>

    <div class="layui-form-item layui-hide">
        <input type="button" lay-submit lay-filter="btn_pig_ok" id="btn_pig_ok" value="确认">
    </div>

</form>
<form class="layui-form" lay-filter="form_pig_item" id="form_pig_item" style="padding: 20px 30px 0 0;display:none;">
    <div class="layui-form-item layui-hide">
        <input type="text" name="id" lay-verify="" placeholder="" autocomplete="off" class="layui-input" style="width: 100%">
        <input type="text" name="addr" lay-verify="" placeholder="" autocomplete="off" class="layui-input" style="width: 100%">
        <input type="text" name="sn" lay-verify="" placeholder="" autocomplete="off" class="layui-input" style="width: 100%">
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label"><span class="layui-text-red">*</span> 猪种</label>
        <div class="layui-input-block">
            <select  name="pig_type" lay-filter="pig_type" lay-verify="required" lay-verType="tips" lay-search="" >
                <option value="" ></option>
            </select>
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label"><span class="layui-text-red">*</span> 耳标号</label>
        <div class="layui-input-block">
            <input type="text" name="earmark" lay-verify="required" lay-verType="tips" placeholder="" autocomplete="off" class="layui-input" style="width: 100%">
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label"> 重量(kg)</label>
        <div class="layui-input-block">
            <input type="text" name="weight"  lay-verType="tips" placeholder="" autocomplete="off" class="layui-input" style="width: 100%">
        </div>
    </div>

    <div class="layui-form-item layui-hide">
        <input type="button" lay-submit lay-filter="btn_pig_item_ok" id="btn_pig_item_ok" value="确认">
    </div>
</form>

<form class="layui-form" lay-filter="form_feed_chart" id="form_feed_chart" style="padding: 2%;height: 90%;display:none;">
    <blockquote class="layui-elem-quote" style="font-size: 0.7rem;margin-bottom: 10px;">
        日采食曲线
        <div class="fr">
            <div class="layui-btn-group day_feed_chart_btns" style="margin-top: 5px;    margin-bottom: 5px;">
                <button type="button" class="layui-btn layui-btn-sm" style="background-color: #3c7cff;" data-type="set" data-key="anim" data-value="day_feed_chart_7day">7日</button>
                <button type="button" class="layui-btn layui-btn-sm " data-type="set" data-key="anim" data-value="day_feed_chart_30day">30日</button>
            </div>
        </div>
    </blockquote>
    <div class="center-block" style="height: calc(55% - 30px);">
        <div id="day_his_chart" style="height: calc(95% - 20px);"></div>
    </div>
    <blockquote class="layui-elem-quote" style="font-size: 0.7rem;margin-bottom: 10px;">
        小时采食曲线
        <div class="fr sebtn">
            <span class="layui-badge-rim fr hand " style="margin: 1px;
            background-color: rgb(255, 255, 255);
            border: 1px solid rgb(255, 158, 24);"><i class="layui-icon layui-icon-date layui-text-sm"></i> <span id="id-date" lay-key=""></span></span>
        </div>
    </blockquote>
    <div class="center-block" style="height: calc(44% - 30px);">
        <div id="hour_his_chart" style="height: 95%"></div>
    </div>
</form>

<form class="layui-form" lay-filter="form-progress" id="form-progress" style="padding: 20px;display:none;">
    <div class="layui-progress layui-progress-big" lay-showpercent="true" lay-filter="progress">
        <div class="layui-progress-bar layui-bg-blue" lay-percent="0%"></div>
    </div>

    <div class="layui-text-black text-center mr-lg" id="progress-tips">批量应用开始...<br /></div>
</form>

<form class="layui-form" lay-filter="form_set_day" id="form_set_day" style="padding: 20px 30px 0 0;display:none;">

    <div class="layui-form-item">
        <label class="layui-form-label"><span class="layui-text-red">*</span> 日龄</label>
        <div class="layui-input-block">
            <input type="text" name="day" lay-verify="number" lay-verType="tips" placeholder="" autocomplete="off" class="layui-input" style="width: 100%">
        </div>
    </div>

    <div class="layui-form-item layui-hide">
        <input type="button" lay-submit lay-filter="on_btn_set_day" id="on_btn_set_day" value="确认">
    </div>
</form>

<form class="layui-form" lay-filter="form_set_waterPTTO" id="form_set_waterPTTO" style="padding: 20px 30px 0 0;display:none;">

    <div class="layui-form-item">
        <label class="layui-form-label"><span class="layui-text-red">*</span> 设置水压</label>
        <div class="layui-input-block">
            <input type="text" name="waterPTTO" lay-verify="number" lay-verType="tips" placeholder="" autocomplete="off" class="layui-input" style="width: 100%">
        </div>
    </div>

    <div class="layui-form-item layui-hide">
        <input type="button" lay-submit lay-filter="on_btn_set_waterPTTO" id="on_btn_set_waterPTTO" value="确认">
    </div>
</form>

<form class="layui-form" lay-filter="form_set_pulseWater" id="form_set_pulseWater" style="padding: 20px 30px 0 0;display:none;">

    <div class="layui-form-item">
        <label class="layui-form-label" style="width: 110px;"><span class="layui-text-red">*</span> 1L水脉冲数</label>
        <div class="layui-input-block" style="margin-left:140px;">
            <!-- <input type="text" name="pulseWater" lay-verify="number" lay-verType="tips" placeholder="" autocomplete="off" class="layui-input" style="width: 100%"> -->
            <select name="pulseWater" lay-filter="pulseWater" lay-verify="number" lay-verType="tips" lay-search=""  >
                <option value="520">520</option>
                <option value="1200">1200</option>
            </select>
        </div>
    </div>

    <div class="layui-form-item layui-hide">
        <input type="button" lay-submit lay-filter="on_btn_set_pulseWater" id="on_btn_set_pulseWater" value="确认">
    </div>
</form>

<form class="layui-form" lay-filter="form_set_calFeed" id="form_set_calFeed" style="padding: 20px 30px 0 0;display:none;">

    <div class="layui-form-item">
        <label class="layui-form-label" style="width: 110px;"><span class="layui-text-red">*</span> 10圈出料数</label>
        <div class="layui-input-block" style="margin-left:140px;">
            <input type="text" name="calFeed" lay-verify="number" maxlength="5" lay-verType="tips" placeholder="" autocomplete="off" class="layui-input" style="width: 100%">
        </div>
    </div>

    <div class="layui-form-item layui-hide">
        <input type="button" lay-submit lay-filter="on_btn_set_calFeed" id="on_btn_set_calFeed" value="确认">
    </div>
</form>


<form class="layui-form" lay-filter="form_set_calAD" id="form_set_calAD" style="padding: 20px 30px 0 0;display:none;">

    <div class="layui-form-item">
        <label class="layui-form-label" style="width: 110px;"><span class="layui-text-red">*</span> 有余料AD值</label>
        <div class="layui-input-block" style="margin-left:140px;">
            <input type="text" name="calAD" lay-verify="number" maxlength="4" lay-verType="tips" placeholder="" autocomplete="off" class="layui-input" style="width: 100%">
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label" style="width: 110px;"><span class="layui-text-red">*</span> 无余料AD值</label>
        <div class="layui-input-block" style="margin-left:140px;">
            <input type="text" name="calADR" lay-verify="number" maxlength="4" lay-verType="tips" placeholder="" autocomplete="off" class="layui-input" style="width: 100%">
        </div>
    </div>

    <div class="layui-form-item layui-hide">
        <input type="button" lay-submit lay-filter="on_btn_set_calAD" id="on_btn_set_calAD" value="确认">
    </div>
</form>

<form class="layui-form" lay-filter="form_manul" id="form_manul" style="padding: 20px;display:none;">
    <div class="layui-form-item layui-hide">
        <input type="text" name="addr" lay-verify="" placeholder="" autocomplete="off" class="layui-input" style="width: 100%">
        <input type="text" name="tn" lay-verify="" placeholder="" autocomplete="off" class="layui-input" style="width: 100%">
    </div>
    <!-- <div class="layui-form-mid layui-word-aux text-center layui-text-xs fr" style="width: 100%;"><i class="layui-text-xs layui-icon layui-icon-about"></i> 注意:填写为0则不执行</div> -->
    <div class="layui-form-item">
        <label class="layui-form-label layui-form-label-sm"><span class="layui-text-red">*</span> 远程下料 </label>
        <div class="layui-input-inline">
            <input type="text" name="feed" lay-verify="number" maxlength="4" lay-verType="tips" placeholder="" autocomplete="off" class="layui-input" style="width: 100%">
        </div>
        <label class="layui-form-label layui-form-label-xs" style="text-align: left;">g</label>
    </div>

    <div class="layui-form-item manul_water">
        <label class="layui-form-label layui-form-label-sm"><span class="layui-text-red">*</span> 远程下水</label>
        <div class="layui-input-inline">
            <input type="text" name="water" lay-verify="number" maxlength="4" lay-verType="tips" placeholder="" autocomplete="off" class="layui-input" style="width: 100%">
        </div>
        <label class="layui-form-label layui-form-label-xs" style="text-align: left;">ml</label>
    </div>

    <div class="layui-form-item layui-hide">
        <input type="button" lay-submit lay-filter="on_btn_manul" id="on_btn_manul" value="确认">
        <input type="button" lay-submit lay-filter="on_btn_manul_batch" id="on_btn_manul_batch" value="确认">
    </div>
</form>


<form class="layui-form" lay-filter="form_auto_hnum" id="form_auto_hnum" style="padding: 20px 30px 0 0;display:none;">

    <div class="layui-form-item">
        <label class="layui-form-label" style="width: 110px;"><span class="layui-text-red">*</span> 起始字母</label>
        <div class="layui-input-block" style="margin-left:140px;">
            <input type="text" value="A" name="prefix_idx" lay-verify="required" maxlength="1" lay-verType="tips" placeholder="A-Z" autocomplete="off" class="layui-input" style="width: 100%">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label" style="width: 110px;"><span class="layui-text-red">*</span> 每排台数</label>
        <div class="layui-input-block" style="margin-left:140px;">
            <input type="text" name="col" lay-verify="number" maxlength="2" lay-verType="tips" placeholder="" autocomplete="off" class="layui-input" style="width: 100%">
        </div>
    </div>

    <div class="layui-form-item layui-hide">
        <input type="button" lay-submit lay-filter="btn_auto_hnum" id="btn_auto_hnum" value="确认">
    </div>
</form>

<!-- <form class="layui-form" lay-filter="form_earmark" id="form_earmark" style="padding: 20px 30px 0 0;display:none;">
    <div class="layui-form-item layui-hide">
        <input type="text" name="addr" lay-verify="" placeholder="" autocomplete="off" class="layui-input" style="width: 100%">
        <input type="text" name="sn" lay-verify="" placeholder="" autocomplete="off" class="layui-input" style="width: 100%">
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label"><span class="layui-text-red">*</span> 耳标号</label>
        <div class="layui-input-block">
            <input type="text" name="earmark" lay-verify="required" lay-verType="tips" placeholder="" autocomplete="off" class="layui-input" style="width: 100%">
        </div>
    </div>


    <div class="layui-form-item layui-hide">
        <input type="button" lay-submit lay-filter="btn_earmark" id="btn_earmark" value="确认">
    </div>
</form>

<form class="layui-form" lay-filter="form_pig_type" id="form_pig_type" style="padding: 20px 30px 0 0;display:none;">
    <div class="layui-form-item layui-hide">
        <input type="text" name="addr" lay-verify="" placeholder="" autocomplete="off" class="layui-input" style="width: 100%">
        <input type="text" name="sn" lay-verify="" placeholder="" autocomplete="off" class="layui-input" style="width: 100%">
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label"><span class="layui-text-red">*</span> 猪种</label>
        <div class="layui-input-block">
            <select  name="pig_type" lay-filter="pig_type" lay-verify="required" lay-verType="tips" lay-search="" >
                <option value="" ></option>
            </select>
        </div>
    </div>


    <div class="layui-form-item layui-hide">
        <input type="button" lay-submit lay-filter="btn_pig_type" id="btn_pig_type" value="确认">
    </div>
</form> -->

<div id="detail" style="display:none;">

    <div class=" layui-tab layui-tab-brief"  style="">
        <ul class="layui-tab-title">
            <li class="layui-this"><i class="layui-icon layui-icon-note "></i> 概要信息 </li>
            
            <li><i class="layui-icon layui-icon-list "></i> 采食详情</li>
            <li><i class="layui-icon layui-icon-notice "></i> 设备报警</li>
        </ul>
        <div class="layui-tab-content">
            <div class="layui-tab-item layui-show">
                <div class="">
                    <div style="margin: 5px;padding: 5px;">

                        <span id="title_online" class="layui-badge layui-bg-green">在线</span>
                        <span id="title_offline" class="layui-badge layui-bg-black">离线</span>
                        <span id="title_disable" class="layui-badge layui-bg-orange">停用</span>
                        <span id="title_alarm" class="layui-badge layui-bg-red"></span>
                        <span id="title_sn" class="layui-badge layui-bg-black"></span>
                        <span id="title_ver" class="layui-badge layui-bg-black"></span>
                        
                        <span id="title_dura" class="layui-badge layui-bg-black"></span>
                    </div>
                    <form class="layui-form" id="form_status" lay-filter="form_status" >

                        <div class="layui-form-item layui-form-item-ext">
                            <div class="layui-inline">
                                <label class="layui-form-label layui-form-label-ext-sm">今日下料</label>
                                <div class="layui-input-inline" style="padding: 9px 15px;">
                                    <div style="width: 310px;" class="layui-progress layui-progress-big" lay-showpercent="true" lay-filter="progress1">
                                        <div class="layui-progress-bar layui-bg-blue" lay-percent="0%"></div>
                                    </div>
                                </div>
                            </div>
                        </div>


                        

                        <div class="layui-form-item layui-form-item-ext">
                            <div class="layui-inline">
                                <label class="layui-form-label layui-form-label-ext-sm">日龄</label>
                                <div class="layui-input-inline">
                                    <input type="text" readonly  name="day" lay-verify="" lay-verType="tips" autocomplete="off" class="layui-input layui-input-ext">
                                </div>
                            </div>

                            <div class="layui-inline">
                                <label class="layui-form-label layui-form-label-ext-sm">模式</label>
                                <div class="layui-input-inline">
                                    <input type="text" readonly  name="mode" lay-verify="" lay-verType="tips" autocomplete="off" class="layui-input layui-input-ext">
                                </div>
                            </div>
                        </div>

                        <div class="layui-form-item layui-form-item-ext">
                            <div class="layui-inline">
                                <label class="layui-form-label layui-form-label-ext-sm">水料比</label>
                                <div class="layui-input-inline">
                                    <input type="text" readonly  name="feed_water" lay-verify="" lay-verType="tips" autocomplete="off" class="layui-input layui-input-ext">
                                </div>
                            </div>
                            <div class="layui-inline">
                                <label class="layui-form-label layui-form-label-ext-sm">日下料目标</label>
                                <div class="layui-input-inline">
                                    <input type="text" readonly  name="max_feed" lay-verify="" lay-verType="tips" autocomplete="off" class="layui-input layui-input-ext">
                                </div>
                            </div>
                        </div>



                        <!--<div class="layui-form-item">
                            <div class="layui-inline">
                                <label class="layui-form-label">时段下料</label>
                                <div class="layui-input-inline">
                                    <input type="text" readonly  name="OutT" lay-verify="" lay-verType="tips" autocomplete="off" class="layui-input">
                                </div>
                            </div>

                            <div class="layui-inline">
                                <label class="layui-form-label">时段已下</label>
                                <div class="layui-input-inline">
                                    <input type="text" readonly  name="TimeUseFeed" lay-verify="" lay-verType="tips" autocomplete="off" class="layui-input">
                                </div>
                            </div>
                        </div>-->

                        <div class="layui-form-item layui-form-item-ext">
                            <div class="layui-inline">
                                <label class="layui-form-label layui-form-label-ext-sm">自动下水</label>
                                <div class="layui-input-inline">
                                    <input type="text" readonly  name="day_use_water_auto" lay-verify="" lay-verType="tips" autocomplete="off" class="layui-input layui-input-ext">
                                </div>
                            </div>

                            <div class="layui-inline">
                                <label class="layui-form-label layui-form-label-ext-sm">自动下料</label>
                                <div class="layui-input-inline">
                                    <input type="text" readonly  name="day_use_feed_auto" lay-verify="" lay-verType="tips" autocomplete="off" class="layui-input layui-input-ext">
                                </div>
                            </div>
                        </div>

                        <div class="layui-form-item layui-form-item-ext">
                            <div class="layui-inline">
                                <label class="layui-form-label layui-form-label-ext-sm">远程下水</label>
                                <div class="layui-input-inline">
                                    <input type="text" readonly  name="day_use_water_man" lay-verify="" lay-verType="tips" autocomplete="off" class="layui-input layui-input-ext">
                                </div>
                            </div>

                            <div class="layui-inline">
                                <label class="layui-form-label layui-form-label-ext-sm">远程下料</label>
                                <div class="layui-input-inline">
                                    <input type="text" readonly  name="day_use_feed_man" lay-verify="" lay-verType="tips" autocomplete="off" class="layui-input layui-input-ext">
                                </div>
                            </div>
                        </div>

                        <div class="layui-form-item layui-form-item-ext">
                            <div class="layui-inline">
                                <label class="layui-form-label layui-form-label-ext-sm">其他信息</label>
                                <div class="layui-input-inline">
                                    <input type="text" readonly  name="other" lay-verify="" lay-verType="tips" autocomplete="off" class="layui-input layui-input-ext">
                                </div>
                            </div>

                            
                        </div>

                    </form>
                </div>
            </div>
           
            <div class="layui-tab-item ">
                <div class="">
                    <div class="layui-btn-group history_btns" style="margin-top: 5px;">
                        <button class="layui-btn layui-btn-sm" style="background-color: #3c7cff;" data-type="set" data-key="anim" data-value="feed_his">下料记录</button>
                        <button class="layui-btn layui-btn-sm " data-type="set" data-key="anim" data-value="water_his">下水记录</button>
                        <button class="layui-btn layui-btn-sm " data-type="set" data-key="anim" data-value="tb_his">触碰记录</button>
                    </div>
                    <div class="feed_his div_his">
                        <table class="layui-hide" id="table_feed_his" lay-filter="table_feed_his"></table>
                    </div>
                    <div class="water_his div_his layui-hide">
                        <table class="layui-hide" id="table_water_his" lay-filter="table_water_his"></table>
                    </div>
                    <div class="tb_his div_his layui-hide">
                        <table class="layui-hide" id="table_tb_his" lay-filter="table_tb_his"></table>
                    </div>
                </div>
            </div>
            <div class="layui-tab-item ">
                <div class="">
                    <div class="layui-btn-group alarm_btns" style="margin-top: 5px;">
                        <button class="layui-btn layui-btn-sm" style="background-color: #3c7cff;" data-type="set" data-key="anim" data-value="alarm_now">当前告警</button>
                        <button class="layui-btn layui-btn-sm " data-type="set" data-key="anim" data-value="alarm_his">告警历史</button>
                    </div>
                    <div class="alarm_now div_alarm">
                        <table class="layui-hide" id="table_alarm_now" lay-filter="table_alarm_now"></table>
                    </div>
                    <div class="alarm_his div_alarm layui-hide">
                        <table class="layui-hide" id="table_alarm_his" lay-filter="table_alarm_his"></table>
                    </div>
                </div>
            </div>
        </div>
    </div>

</div>


<div id="op_his" style="display:none;">
    <div class=" layui-tab layui-tab-brief" >
        <ul class="layui-tab-title">
            <li class="layui-this">方案记录</li>
            <li>日龄记录</li>
            <li>校准记录</li>
        </ul>
        <div class="layui-tab-content">
            <div class="layui-tab-item layui-show">
                <table class="layui-hide" id="table_op_log_set_para" lay-filter="table_op_log_set_para"></table>
            </div>
            <div class="layui-tab-item">
                <table class="layui-hide" id="table_op_log_set_day" lay-filter="table_op_log_set_day"></table>
            </div>
            <div class="layui-tab-item">
                <table class="layui-hide" id="table_op_log_set_calc" lay-filter="table_op_log_set_calc"></table>
            </div>
        </div>
    </div>
</div>

</html>